Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files
app.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
core.py
CHANGED
|
@@ -14,6 +14,8 @@ Fixes vs previous version:
|
|
| 14 |
Retries up to 3x, strips explicit Hs from receptor, polls up to 120 s.
|
| 15 |
- warm_poseview_cache: now a no-op (MoleculeHandler pre-upload removed)
|
| 16 |
- call_poseview2_ref: retry + full-response logging
|
|
|
|
|
|
|
| 17 |
- Minor: type annotations, cleaner log messages
|
| 18 |
"""
|
| 19 |
|
|
@@ -56,6 +58,8 @@ COFACTOR_NAMES = {
|
|
| 56 |
"EPE", "MES", "TRS", "ACT", "ACY",
|
| 57 |
}
|
| 58 |
|
|
|
|
|
|
|
| 59 |
# PoseView: max retries on "failure" before giving up
|
| 60 |
_PV_MAX_RETRIES = 3
|
| 61 |
# PoseView: seconds to wait between retries
|
|
@@ -276,50 +280,110 @@ def get_vina_binary(path: str = ""):
|
|
| 276 |
# RECEPTOR PREPARATION
|
| 277 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 278 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
def detect_cocrystal_ligand(raw_pdb: str) -> dict:
|
| 280 |
"""
|
| 281 |
-
Parse PDB and return the best co-crystal ligand candidate
|
|
|
|
|
|
|
|
|
|
| 282 |
Returns dict with keys:
|
| 283 |
found, resname, chain, resid, sel_str, ligand_id,
|
| 284 |
cx, cy, cz, n_atoms, atoms
|
| 285 |
"""
|
| 286 |
-
from prody import parsePDB
|
| 287 |
|
| 288 |
atoms = parsePDB(raw_pdb)
|
| 289 |
if atoms is None:
|
| 290 |
return {"found": False}
|
| 291 |
|
| 292 |
-
|
| 293 |
-
het = atoms.select("hetero and not water")
|
| 294 |
-
if het is None:
|
| 295 |
-
return {"found": False}
|
| 296 |
-
|
| 297 |
-
cands = [
|
| 298 |
-
r for r in het.getHierView().iterResidues()
|
| 299 |
-
if (r.getResname() or "").strip() not in excl
|
| 300 |
-
]
|
| 301 |
if not cands:
|
| 302 |
return {"found": False}
|
| 303 |
|
| 304 |
-
|
| 305 |
-
chosen = cands[0]
|
| 306 |
-
rn = chosen.getResname()
|
| 307 |
-
ch = chosen.getChid()
|
| 308 |
-
ri = chosen.getResnum()
|
| 309 |
-
sel_str = f"resname {rn} and resid {ri} and chain {ch}"
|
| 310 |
-
lig_atoms = atoms.select(sel_str)
|
| 311 |
-
cx, cy, cz = (float(v) for v in calcCenter(lig_atoms))
|
| 312 |
-
|
| 313 |
return {
|
| 314 |
"found": True,
|
| 315 |
-
"resname":
|
| 316 |
-
"chain":
|
| 317 |
-
"resid":
|
| 318 |
-
"sel_str": sel_str,
|
| 319 |
-
"ligand_id":
|
| 320 |
-
"cx": cx, "cy": cy, "cz": cz,
|
| 321 |
-
"n_atoms":
|
| 322 |
-
"atoms":
|
| 323 |
}
|
| 324 |
|
| 325 |
|
|
@@ -508,27 +572,40 @@ def prepare_receptor(
|
|
| 508 |
ri = 0
|
| 509 |
cx = cy = cz = 0.0
|
| 510 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
if center_mode == "auto":
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
ligand_sel_str = info["sel_str"]
|
| 516 |
-
cocrystal_ligand_id = info["ligand_id"]
|
| 517 |
-
cx, cy, cz = info["cx"], info["cy"], info["cz"]
|
| 518 |
-
ligand_pdb_path = str(wdir / "LIG.pdb")
|
| 519 |
-
writePDB(ligand_pdb_path, info["atoms"])
|
| 520 |
-
log.append(
|
| 521 |
-
f"✓ Co-crystal ligand: {rn} chain {ch} resnum {ri} "
|
| 522 |
-
f"({info['n_atoms']} atoms)"
|
| 523 |
-
)
|
| 524 |
-
log.append(f"📍 Center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
|
| 525 |
log.append(f"🔑 PoseView2 ligand ID: {cocrystal_ligand_id}")
|
| 526 |
else:
|
| 527 |
-
log.append("⚠ No co-crystal ligand found
|
| 528 |
|
| 529 |
elif center_mode == "manual":
|
| 530 |
cx, cy, cz = (float(v) for v in manual_xyz)
|
| 531 |
log.append(f"🛠 Manual center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
|
|
|
|
|
|
|
| 532 |
|
| 533 |
elif center_mode == "selection":
|
| 534 |
if not prody_sel.strip():
|
|
@@ -544,35 +621,24 @@ def prepare_receptor(
|
|
| 544 |
f"→ {ref_atoms.numAtoms()} atoms"
|
| 545 |
)
|
| 546 |
log.append(f"📍 Center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
|
| 547 |
-
|
| 548 |
-
# The ProDy selection positions the docking box only.
|
| 549 |
-
# Co-crystal ligand detection, receptor stripping, ligand PDB
|
| 550 |
-
# saving, and PoseView2 ID are handled identically to 'auto' mode
|
| 551 |
-
# so that RMSD calculation, 3D viewer, and 2D interaction diagrams
|
| 552 |
-
# all work correctly regardless of what the user selected.
|
| 553 |
-
info = detect_cocrystal_ligand(raw_pdb)
|
| 554 |
-
if info["found"]:
|
| 555 |
-
rn, ch, ri = info["resname"], info["chain"], info["resid"]
|
| 556 |
-
ligand_sel_str = info["sel_str"]
|
| 557 |
-
cocrystal_ligand_id = info["ligand_id"]
|
| 558 |
-
ligand_pdb_path = str(wdir / "LIG.pdb")
|
| 559 |
-
writePDB(ligand_pdb_path, info["atoms"])
|
| 560 |
-
log.append(
|
| 561 |
-
f"✓ Co-crystal ligand: {rn} chain {ch} resnum {ri} "
|
| 562 |
-
f"({info['n_atoms']} atoms)"
|
| 563 |
-
)
|
| 564 |
log.append(f"🔑 PoseView2 ligand ID: {cocrystal_ligand_id}")
|
| 565 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
log.append(
|
| 567 |
-
"
|
| 568 |
-
"
|
| 569 |
)
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
sel_str = (
|
| 573 |
-
f"not ({ligand_sel_str}) and not water"
|
| 574 |
-
if ligand_sel_str else "not water"
|
| 575 |
-
)
|
| 576 |
rec_sel = atoms.select(sel_str)
|
| 577 |
if rec_sel is None or rec_sel.numAtoms() == 0:
|
| 578 |
raise ValueError("Receptor selection returned no atoms")
|
|
@@ -581,6 +647,31 @@ def prepare_receptor(
|
|
| 581 |
writePDB(rec_raw_path, rec_sel)
|
| 582 |
log.append(f"✓ Receptor: {rec_sel.numAtoms()} atoms")
|
| 583 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
# PDBQT conversion (metal-safe)
|
| 585 |
conv = strip_and_convert_receptor(rec_raw_path, wdir)
|
| 586 |
log.extend(conv["log"])
|
|
@@ -729,7 +820,6 @@ def prepare_ligand_from_file(file_path: str, name: str, wdir) -> dict:
|
|
| 729 |
if mols:
|
| 730 |
mol = mols[0]
|
| 731 |
elif ext in (".mol2", ".pdb"):
|
| 732 |
-
# Strategy A: convert via obabel first (handles GaussView bond types)
|
| 733 |
_ob_sdf = str(wdir / f"{name}_ob.sdf")
|
| 734 |
import subprocess
|
| 735 |
subprocess.run(
|
|
@@ -745,7 +835,6 @@ def prepare_ligand_from_file(file_path: str, name: str, wdir) -> dict:
|
|
| 745 |
if mols:
|
| 746 |
mol = mols[0]
|
| 747 |
log.append("✓ Converted via OpenBabel")
|
| 748 |
-
# Strategy B: direct RDKit read as fallback
|
| 749 |
if mol is None:
|
| 750 |
if ext == ".mol2":
|
| 751 |
mol = Chem.MolFromMol2File(file_path, removeHs=False, sanitize=True)
|
|
@@ -759,14 +848,12 @@ def prepare_ligand_from_file(file_path: str, name: str, wdir) -> dict:
|
|
| 759 |
if mol is None:
|
| 760 |
raise ValueError(f"Could not read molecule from {Path(file_path).name}")
|
| 761 |
|
| 762 |
-
# Keep only the largest fragment if multiple exist
|
| 763 |
frags = Chem.GetMolFrags(mol, asMols=True, sanitizeFrags=False)
|
| 764 |
if len(frags) > 1:
|
| 765 |
frags = sorted(frags, key=lambda m: m.GetNumAtoms(), reverse=True)
|
| 766 |
mol = frags[0]
|
| 767 |
log.append(f"⚠ {len(frags)} fragments — kept largest ({mol.GetNumAtoms()} atoms)")
|
| 768 |
|
| 769 |
-
# Try to sanitize if not already done
|
| 770 |
try:
|
| 771 |
Chem.SanitizeMol(mol)
|
| 772 |
except Exception:
|
|
@@ -774,7 +861,6 @@ def prepare_ligand_from_file(file_path: str, name: str, wdir) -> dict:
|
|
| 774 |
|
| 775 |
log.append("✓ Loaded molecule from file (no protonation)")
|
| 776 |
|
| 777 |
-
# Get SMILES for display / downstream use
|
| 778 |
try:
|
| 779 |
smi = Chem.MolToSmiles(Chem.RemoveHs(mol))
|
| 780 |
except Exception:
|
|
@@ -788,11 +874,9 @@ def prepare_ligand_from_file(file_path: str, name: str, wdir) -> dict:
|
|
| 788 |
charge = 0
|
| 789 |
log.append(f"✓ Formal charge: {charge:+d}")
|
| 790 |
|
| 791 |
-
# Ensure ALL hydrogens are explicit (Meeko requirement)
|
| 792 |
mol = Chem.AddHs(mol, addCoords=True)
|
| 793 |
log.append("✓ All hydrogens made explicit")
|
| 794 |
|
| 795 |
-
# Check if 3D coordinates exist; generate if missing
|
| 796 |
conf = mol.GetConformer(0) if mol.GetNumConformers() > 0 else None
|
| 797 |
if conf is None or conf.Is3D() is False:
|
| 798 |
try:
|
|
@@ -972,18 +1056,12 @@ def _bo_fix_mol(probe, template):
|
|
| 972 |
def fix_sdf_bond_orders(raw_sdf: str, smiles: str, fixed_sdf: str) -> list:
|
| 973 |
"""
|
| 974 |
Apply bond-order + formal-charge correction to all poses in an SDF.
|
| 975 |
-
|
| 976 |
-
FIX: Adds Hs with addCoords=True to preserve docked pose coordinates.
|
| 977 |
-
Validates that no H atom landed at origin before writing with Hs.
|
| 978 |
-
Falls back to heavy-atom-only mol if addCoords fails.
|
| 979 |
-
|
| 980 |
Returns list of log messages.
|
| 981 |
"""
|
| 982 |
import shutil
|
| 983 |
from rdkit import Chem, RDLogger
|
| 984 |
from rdkit.Chem import AllChem
|
| 985 |
|
| 986 |
-
# Suppress kekulize noise from raw Vina SDF
|
| 987 |
RDLogger.DisableLog("rdApp.*")
|
| 988 |
|
| 989 |
log = []
|
|
@@ -1009,11 +1087,9 @@ def fix_sdf_bond_orders(raw_sdf: str, smiles: str, fixed_sdf: str) -> list:
|
|
| 1009 |
try:
|
| 1010 |
fixed = _bo_fix_mol(mol, template)
|
| 1011 |
|
| 1012 |
-
# Add Hs with real 3D coordinates (preserves docked pose)
|
| 1013 |
try:
|
| 1014 |
fixed_h = Chem.AddHs(fixed, addCoords=True)
|
| 1015 |
conf = fixed_h.GetConformer()
|
| 1016 |
-
# Reject if any H landed at origin (addCoords=True failed silently)
|
| 1017 |
bad = any(
|
| 1018 |
abs(conf.GetAtomPosition(j).x)
|
| 1019 |
+ abs(conf.GetAtomPosition(j).y)
|
|
@@ -1023,7 +1099,6 @@ def fix_sdf_bond_orders(raw_sdf: str, smiles: str, fixed_sdf: str) -> list:
|
|
| 1023 |
)
|
| 1024 |
writer.write(fixed if bad else fixed_h)
|
| 1025 |
except Exception:
|
| 1026 |
-
# Fallback: heavy atoms only — PoseView can add its own Hs
|
| 1027 |
writer.write(fixed)
|
| 1028 |
|
| 1029 |
ok += 1
|
|
@@ -1044,16 +1119,9 @@ def fix_sdf_bond_orders(raw_sdf: str, smiles: str, fixed_sdf: str) -> list:
|
|
| 1044 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 1045 |
|
| 1046 |
def load_mols_from_sdf(sdf_path: str, sanitize: bool = True) -> list:
|
| 1047 |
-
"""
|
| 1048 |
-
Load all valid mols from an SDF file.
|
| 1049 |
-
|
| 1050 |
-
FIX: Suppresses RDKit kekulize / sanitize noise from raw Vina output SDFs.
|
| 1051 |
-
Falls back to per-mol sanitize on failure so poses are never silently lost.
|
| 1052 |
-
"""
|
| 1053 |
from rdkit import Chem, RDLogger
|
| 1054 |
|
| 1055 |
-
# Suppress "Can't kekulize" / sanitize errors —
|
| 1056 |
-
# Vina SDF aromatic bonds cause these on every pose when sanitize=True.
|
| 1057 |
RDLogger.DisableLog("rdApp.*")
|
| 1058 |
|
| 1059 |
mols = []
|
|
@@ -1065,7 +1133,6 @@ def load_mols_from_sdf(sdf_path: str, sanitize: bool = True) -> list:
|
|
| 1065 |
except Exception:
|
| 1066 |
pass
|
| 1067 |
|
| 1068 |
-
# If sanitize=True produced 0 (or fewer than raw), fall back per-mol
|
| 1069 |
if sanitize:
|
| 1070 |
try:
|
| 1071 |
sup2 = Chem.SDMolSupplier(sdf_path, sanitize=False, removeHs=False)
|
|
@@ -1076,7 +1143,7 @@ def load_mols_from_sdf(sdf_path: str, sanitize: bool = True) -> list:
|
|
| 1076 |
try:
|
| 1077 |
Chem.SanitizeMol(m)
|
| 1078 |
except Exception:
|
| 1079 |
-
pass
|
| 1080 |
result.append(m)
|
| 1081 |
RDLogger.EnableLog("rdApp.error")
|
| 1082 |
return result
|
|
@@ -1095,32 +1162,15 @@ def write_single_pose(mol, path: str) -> None:
|
|
| 1095 |
|
| 1096 |
|
| 1097 |
def convert_sdf_to_v2000(sdf_path: str) -> str:
|
| 1098 |
-
"""
|
| 1099 |
-
Convert an SDF to Kekulized V2000 format suitable for PoseView.
|
| 1100 |
-
|
| 1101 |
-
PoseView's bundled CDK mol parser requires:
|
| 1102 |
-
- V2000 format (not V3000)
|
| 1103 |
-
- Fully Kekulized bonds: explicit single/double (type 1/2), NOT aromatic
|
| 1104 |
-
bond type 4. obabel preserves aromatic type 4 which PoseView rejects.
|
| 1105 |
-
- No explicit Hs (PoseView adds its own for H-bond detection)
|
| 1106 |
-
|
| 1107 |
-
Strategy:
|
| 1108 |
-
1. RDKit: read → RemoveHs → Kekulize → SDWriter(SetKekulize=True)
|
| 1109 |
-
This is the canonical fix — guarantees type-1/2 bond encoding.
|
| 1110 |
-
2. Fallback: obabel plain format conversion (no -h, no --gen3d).
|
| 1111 |
-
|
| 1112 |
-
Returns path to converted file, or original sdf_path on failure.
|
| 1113 |
-
"""
|
| 1114 |
from rdkit import Chem, RDLogger
|
| 1115 |
|
| 1116 |
out = sdf_path.replace(".sdf", "_v2000.sdf")
|
| 1117 |
if out == sdf_path:
|
| 1118 |
out = sdf_path + "_v2000.sdf"
|
| 1119 |
|
| 1120 |
-
# ── Strategy 1: RDKit Kekulized V2000 ─────────────────────────────────────
|
| 1121 |
RDLogger.DisableLog("rdApp.*")
|
| 1122 |
try:
|
| 1123 |
-
# Try sanitized read first; fall back to unsanitized
|
| 1124 |
mol = None
|
| 1125 |
for sanitize in (True, False):
|
| 1126 |
sup = Chem.SDMolSupplier(sdf_path, sanitize=sanitize, removeHs=True)
|
|
@@ -1139,15 +1189,13 @@ def convert_sdf_to_v2000(sdf_path: str) -> str:
|
|
| 1139 |
Chem.SanitizeMol(mol_noH)
|
| 1140 |
except Exception:
|
| 1141 |
pass
|
| 1142 |
-
# Kekulize: convert aromatic bonds → alternating single/double
|
| 1143 |
-
# PoseView rejects MDL bond type 4 (aromatic)
|
| 1144 |
try:
|
| 1145 |
Chem.Kekulize(mol_noH, clearAromaticFlags=True)
|
| 1146 |
except Exception:
|
| 1147 |
-
pass
|
| 1148 |
|
| 1149 |
w = Chem.SDWriter(out)
|
| 1150 |
-
w.SetKekulize(True)
|
| 1151 |
w.write(mol_noH)
|
| 1152 |
w.close()
|
| 1153 |
|
|
@@ -1158,7 +1206,6 @@ def convert_sdf_to_v2000(sdf_path: str) -> str:
|
|
| 1158 |
pass
|
| 1159 |
RDLogger.EnableLog("rdApp.error")
|
| 1160 |
|
| 1161 |
-
# ── Strategy 2: obabel plain conversion (no -h, no --gen3d) ──────────────
|
| 1162 |
rc, _ = run_cmd(f'obabel "{sdf_path}" -O "{out}" 2>/dev/null')
|
| 1163 |
if rc == 0 and os.path.exists(out) and os.path.getsize(out) > 10:
|
| 1164 |
return out
|
|
@@ -1320,10 +1367,7 @@ _PP_PROTEIN_CACHE: dict = {}
|
|
| 1320 |
|
| 1321 |
def _pp_poll(job_id: str, poll_url: str, poll_interval: int = 2,
|
| 1322 |
max_polls: int = 60) -> dict:
|
| 1323 |
-
"""
|
| 1324 |
-
Poll a ProteinsPlus job until it leaves pending/running state.
|
| 1325 |
-
Returns the final job dict. Raises RuntimeError on timeout.
|
| 1326 |
-
"""
|
| 1327 |
import requests
|
| 1328 |
job = requests.get(poll_url + job_id + "/", headers=_PP_HEADERS, timeout=15).json()
|
| 1329 |
status = str(job.get("status", "")).lower()
|
|
@@ -1342,22 +1386,7 @@ def _pp_poll(job_id: str, poll_url: str, poll_interval: int = 2,
|
|
| 1342 |
|
| 1343 |
|
| 1344 |
def _prepare_pdb_for_poseview(receptor_pdb: str) -> str:
|
| 1345 |
-
"""
|
| 1346 |
-
Write a minimal, clean PDB suitable for PoseView's CDK-based parser.
|
| 1347 |
-
|
| 1348 |
-
PoseView's Java engine is strict:
|
| 1349 |
-
- Accepts only ATOM / HETATM / TER / END records
|
| 1350 |
-
- Chokes on ANISOU, SIGUIJ, CONECT, non-standard REMARK variants
|
| 1351 |
-
- Must have no explicit Hs (PoseView adds its own for H-bond detection)
|
| 1352 |
-
- Serial numbers must be contiguous integers
|
| 1353 |
-
|
| 1354 |
-
Source priority:
|
| 1355 |
-
1. receptor_atoms.pdb in the same directory — ProDy writePDB, cleanest
|
| 1356 |
-
2. The passed receptor_pdb (obabel-processed rec.pdb)
|
| 1357 |
-
|
| 1358 |
-
Returns path to the clean PDB, or original path on any failure.
|
| 1359 |
-
"""
|
| 1360 |
-
# Prefer ProDy's clean output over obabel's processed file
|
| 1361 |
rec_dir = os.path.dirname(os.path.abspath(receptor_pdb))
|
| 1362 |
candidates = [
|
| 1363 |
os.path.join(rec_dir, "receptor_atoms.pdb"),
|
|
@@ -1372,29 +1401,20 @@ def _prepare_pdb_for_poseview(receptor_pdb: str) -> str:
|
|
| 1372 |
with open(source) as f:
|
| 1373 |
for line in f:
|
| 1374 |
rec = line[:6].strip()
|
| 1375 |
-
|
| 1376 |
-
# Only standard coordinate records
|
| 1377 |
if rec not in ("ATOM", "HETATM", "TER", "END"):
|
| 1378 |
continue
|
| 1379 |
-
|
| 1380 |
if rec in ("ATOM", "HETATM"):
|
| 1381 |
-
# Strip hydrogen atoms
|
| 1382 |
atom_name = line[12:16].strip()
|
| 1383 |
element = line[76:78].strip() if len(line) > 76 else ""
|
| 1384 |
if element.upper() == "H" or (not element and atom_name.startswith("H")):
|
| 1385 |
continue
|
| 1386 |
-
|
| 1387 |
-
# Renumber serials to stay contiguous (PDBs from obabel
|
| 1388 |
-
# can have gaps after H removal that confuse CDK)
|
| 1389 |
serial += 1
|
| 1390 |
line = f"{line[:6]}{serial:5d}{line[11:]}"
|
| 1391 |
-
|
| 1392 |
kept.append(line if line.endswith("\n") else line + "\n")
|
| 1393 |
|
| 1394 |
if not kept:
|
| 1395 |
return receptor_pdb
|
| 1396 |
|
| 1397 |
-
# Ensure file ends with END
|
| 1398 |
if not any(l.startswith("END") for l in kept):
|
| 1399 |
kept.append("END\n")
|
| 1400 |
|
|
@@ -1412,42 +1432,17 @@ def _prepare_pdb_for_poseview(receptor_pdb: str) -> str:
|
|
| 1412 |
def call_poseview_v1(receptor_pdb: str, pose_sdf: str) -> tuple:
|
| 1413 |
"""
|
| 1414 |
Submit receptor PDB + docked pose SDF to PoseView v1 REST API.
|
| 1415 |
-
|
| 1416 |
-
Submits a clean receptor PDB + raw pose SDF directly to PoseView v1.
|
| 1417 |
-
|
| 1418 |
-
KEY FINDING: the raw pose SDF (as downloaded by the user) works when
|
| 1419 |
-
uploaded manually to proteins.plus. All previous SDF transforms
|
| 1420 |
-
(fix_sdf_bond_orders → convert_sdf_to_v2000) were corrupting the file.
|
| 1421 |
-
Solution: send pose_sdf as-is — zero transformation.
|
| 1422 |
-
|
| 1423 |
-
Protein: _prepare_pdb_for_poseview strips non-coordinate records,
|
| 1424 |
-
removes Hs, renumbers serials — using receptor_atoms.pdb (ProDy) as
|
| 1425 |
-
source where available (cleaner than obabel-processed rec.pdb).
|
| 1426 |
-
|
| 1427 |
-
Flow:
|
| 1428 |
-
1 — _prepare_pdb_for_poseview → clean PDB
|
| 1429 |
-
2 — POST receptor + raw pose_sdf directly to /api/v2/poseview/
|
| 1430 |
-
3 — Poll → GET job['image'] SVG
|
| 1431 |
-
|
| 1432 |
Returns (svg_bytes, error_string) — one will be None.
|
| 1433 |
"""
|
| 1434 |
import requests
|
| 1435 |
|
| 1436 |
last_error = "Unknown error"
|
| 1437 |
-
|
| 1438 |
-
# Clean the receptor once — CDK-safe: only ATOM/HETATM/TER/END,
|
| 1439 |
-
# no Hs, contiguous serials, sourced from ProDy receptor_atoms.pdb.
|
| 1440 |
rec_to_send = _prepare_pdb_for_poseview(receptor_pdb)
|
| 1441 |
|
| 1442 |
for attempt in range(1, _PV_MAX_RETRIES + 1):
|
| 1443 |
if attempt > 1:
|
| 1444 |
time.sleep(_PV_RETRY_DELAY)
|
| 1445 |
|
| 1446 |
-
# ── POST receptor + raw SDF directly to PoseView ──────────────────────
|
| 1447 |
-
# IMPORTANT: send pose_sdf as-is — no bond-order fixing, no V2000
|
| 1448 |
-
# conversion. The raw Vina→obabel SDF is exactly what the user
|
| 1449 |
-
# downloads and what works when uploaded manually. Any transform
|
| 1450 |
-
# (fix_sdf_bond_orders, convert_sdf_to_v2000) was corrupting the file.
|
| 1451 |
try:
|
| 1452 |
with open(rec_to_send) as rf, open(pose_sdf) as lf:
|
| 1453 |
r = requests.post(
|
|
@@ -1469,7 +1464,6 @@ def call_poseview_v1(receptor_pdb: str, pose_sdf: str) -> tuple:
|
|
| 1469 |
last_error = f"PoseView submission failed (attempt {attempt}): {e}"
|
| 1470 |
continue
|
| 1471 |
|
| 1472 |
-
# ── Step 3: Poll + fetch SVG ──────────────────────────────────────────
|
| 1473 |
try:
|
| 1474 |
pv_job = _pp_poll(pv_job_id, _PP_POSEVIEW_JOBS)
|
| 1475 |
status = str(pv_job.get("status", "")).lower()
|
|
@@ -1512,11 +1506,7 @@ def call_poseview_v1(receptor_pdb: str, pose_sdf: str) -> tuple:
|
|
| 1512 |
|
| 1513 |
|
| 1514 |
def warm_poseview_cache(receptor_pdb: str) -> tuple:
|
| 1515 |
-
"""
|
| 1516 |
-
No-op — call_poseview_v1 now posts the receptor directly to PoseView
|
| 1517 |
-
without a MoleculeHandler/Protoss pre-upload step, so there is nothing
|
| 1518 |
-
to pre-cache. Kept for API compatibility with app.py.
|
| 1519 |
-
"""
|
| 1520 |
return True, "Direct POST mode — no pre-upload needed"
|
| 1521 |
|
| 1522 |
|
|
@@ -1533,7 +1523,6 @@ def call_poseview2_ref(pdb_code: str, ligand_id: str) -> tuple:
|
|
| 1533 |
import requests
|
| 1534 |
|
| 1535 |
_SUBMIT = "https://proteins.plus/api/poseview2_rest"
|
| 1536 |
-
|
| 1537 |
last_error = "Unknown error"
|
| 1538 |
|
| 1539 |
for attempt in range(1, _PV_MAX_RETRIES + 1):
|
|
@@ -1632,10 +1621,7 @@ def svg_to_png(svg_bytes: bytes):
|
|
| 1632 |
|
| 1633 |
|
| 1634 |
def stamp_png(png_bytes: bytes, text: str) -> bytes:
|
| 1635 |
-
"""
|
| 1636 |
-
Burn a centred label pill into the bottom of a PNG.
|
| 1637 |
-
Returns original bytes unchanged on any error.
|
| 1638 |
-
"""
|
| 1639 |
try:
|
| 1640 |
from PIL import Image, ImageDraw, ImageFont
|
| 1641 |
import io as _io
|
|
@@ -1690,11 +1676,7 @@ def stamp_png(png_bytes: bytes, text: str) -> bytes:
|
|
| 1690 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 1691 |
|
| 1692 |
def diagnose_poseview() -> dict:
|
| 1693 |
-
"""
|
| 1694 |
-
Test the PoseView API with a known-good minimal PDB + SDF from RCSB,
|
| 1695 |
-
completely independent of the user's receptor/ligand files.
|
| 1696 |
-
Uses PDB 4AGN + its native ligand NXG fetched live from proteins.plus.
|
| 1697 |
-
"""
|
| 1698 |
import requests
|
| 1699 |
|
| 1700 |
result = {
|
|
@@ -1789,35 +1771,7 @@ def diagnose_poseview() -> dict:
|
|
| 1789 |
|
| 1790 |
|
| 1791 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 1792 |
-
# CUSTOM 2D INTERACTION DIAGRAM
|
| 1793 |
-
#
|
| 1794 |
-
# Decoded from Adobe Illustrator SVG:
|
| 1795 |
-
#
|
| 1796 |
-
# HYDROPHOBIC st6/st16: NO line. Translucent blue circle (#2287ff op 0.2)
|
| 1797 |
-
# + blue 23px bold label. Nothing else.
|
| 1798 |
-
#
|
| 1799 |
-
# H-BOND st13/st15/st2/st1:
|
| 1800 |
-
# Green dashed line (#1a7a1a, dasharray 5 3, 1.6px, op 0.85)
|
| 1801 |
-
# + translucent green circle (#80dd80 op 0.2) r=39.52
|
| 1802 |
-
# + green 23px bold label
|
| 1803 |
-
# + green 14px distance label on line
|
| 1804 |
-
#
|
| 1805 |
-
# π-π st5/st11/st3:
|
| 1806 |
-
# Magenta dashed line (#e200e8, dasharray 5 3, 1.6px, op 0.85)
|
| 1807 |
-
# FROM aromatic ring centroid in ligand → residue position
|
| 1808 |
-
# + translucent magenta circle (#e200e8 op 0.2) r=39.52
|
| 1809 |
-
# + magenta 23px bold label
|
| 1810 |
-
#
|
| 1811 |
-
# LIGAND: st4 single/arom bond: 1.77px, op 0.9
|
| 1812 |
-
# st10 double bond: 2.44px, op 0.9
|
| 1813 |
-
# st14 aromatic circle: 1.77px, op 0.7, dasharray 5.43 2.72
|
| 1814 |
-
# st18 green dot: r=5.43, fill #1a7a1a
|
| 1815 |
-
# st0 N text: #1a5fa8 17.65px bold
|
| 1816 |
-
# st12 O text: #c22 17.65px bold
|
| 1817 |
-
#
|
| 1818 |
-
# TITLE: st19 pill fill #f2f2f2, st7 text 24.93px bold
|
| 1819 |
-
# LEGEND: small colored circles (r=9.54) + gray 16px text
|
| 1820 |
-
# legend box: stroke #f2f2f2 only, no fill bg
|
| 1821 |
# ═══════════════════════════════════════════════════════════════════════════��══
|
| 1822 |
|
| 1823 |
import math as _math
|
|
@@ -1827,42 +1781,40 @@ _ITYPE_PRIORITY = [
|
|
| 1827 |
"hbond", "pi_pi", "cation_pi", "hydrophobic",
|
| 1828 |
]
|
| 1829 |
|
| 1830 |
-
|
| 1831 |
-
|
| 1832 |
-
|
| 1833 |
-
_CLR_HYDRO = "#2287ff" # st6/st16
|
| 1834 |
_CLR_IONIC = "#aa0077"
|
| 1835 |
_CLR_METAL = "#cc8800"
|
| 1836 |
_CLR_HAL = "#cc2277"
|
| 1837 |
_CLR_HBXHAL = "#6633aa"
|
| 1838 |
|
| 1839 |
-
# Residue circle backgrounds (fill + opacity) from SVG
|
| 1840 |
_RES_CIRCLE = {
|
| 1841 |
-
"hbond": dict(fill="#80dd80", opacity=0.2),
|
| 1842 |
"hbond_to_halogen": dict(fill="#80dd80", opacity=0.2),
|
| 1843 |
-
"pi_pi": dict(fill="#e200e8", opacity=0.2),
|
| 1844 |
"cation_pi": dict(fill="#e200e8", opacity=0.2),
|
| 1845 |
-
"hydrophobic": dict(fill="#2287ff", opacity=0.2),
|
| 1846 |
"ionic": dict(fill="#ffaae0", opacity=0.2),
|
| 1847 |
"metal": dict(fill="#ffe080", opacity=0.2),
|
| 1848 |
"halogen": dict(fill="#ffb0d0", opacity=0.2),
|
| 1849 |
}
|
| 1850 |
|
| 1851 |
_LBL_CLR = {
|
| 1852 |
-
"hbond": _CLR_HBOND,
|
| 1853 |
"hbond_to_halogen": _CLR_HBOND,
|
| 1854 |
-
"pi_pi": _CLR_PIPI,
|
| 1855 |
"cation_pi": _CLR_PIPI,
|
| 1856 |
-
"hydrophobic": _CLR_HYDRO,
|
| 1857 |
"ionic": _CLR_IONIC,
|
| 1858 |
"metal": _CLR_METAL,
|
| 1859 |
"halogen": _CLR_HAL,
|
| 1860 |
}
|
| 1861 |
|
| 1862 |
_LINE_CLR = {
|
| 1863 |
-
"hbond": _CLR_HBOND,
|
| 1864 |
"hbond_to_halogen": _CLR_HBXHAL,
|
| 1865 |
-
"pi_pi": _CLR_PIPI,
|
| 1866 |
"cation_pi": _CLR_PIPI,
|
| 1867 |
"ionic": _CLR_IONIC,
|
| 1868 |
"metal": _CLR_METAL,
|
|
@@ -1875,15 +1827,29 @@ _ATOM_CLR = {
|
|
| 1875 |
"S":"#c8a800", "P":"#e07000", "F":"#1a7a1a",
|
| 1876 |
"CL":"#1a7a1a", "BR":"#8b2500", "I":"#5c2d8a", "H":"#555555",
|
| 1877 |
}
|
| 1878 |
-
_AROM_DOT_CLR = "#1a7a1a"
|
| 1879 |
|
| 1880 |
_METALS_SET = {"MG","ZN","CA","MN","FE","CU","CO","NI","CD","HG","NA","K"}
|
| 1881 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1882 |
_AROM_ATOM_NAMES = {
|
|
|
|
| 1883 |
"CG","CD1","CD2","CE1","CE2","CZ",
|
| 1884 |
"ND1","NE2","CE3","CZ2","CZ3","CH2",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1885 |
}
|
| 1886 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1887 |
|
| 1888 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 1889 |
# INTERACTION DETECTION
|
|
@@ -1902,7 +1868,7 @@ def _get_aromatic_ring_data(mol, conf):
|
|
| 1902 |
v1 = coords[1]-coords[0]; v2 = coords[2]-coords[0]
|
| 1903 |
n = np.cross(v1,v2); nl = np.linalg.norm(n)
|
| 1904 |
if nl > 0: n /= nl
|
| 1905 |
-
results.append((centroid, n, list(ring)))
|
| 1906 |
return results
|
| 1907 |
|
| 1908 |
|
|
@@ -1910,14 +1876,8 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 1910 |
cutoff: float = 4.5) -> list:
|
| 1911 |
"""
|
| 1912 |
Detect protein-ligand interactions with proper geometry criteria.
|
| 1913 |
-
|
| 1914 |
-
|
| 1915 |
-
proper HBD/HBA atom-name tables for protein
|
| 1916 |
-
Halogen : C-X···A ≥ 140° + X···A-R ≥ 90° + vdW-sum distance
|
| 1917 |
-
Others : hydrophobic, ionic, metal, π-π, cation-π (unchanged)
|
| 1918 |
-
|
| 1919 |
-
All inner loops replaced with numpy vectorised distance/angle
|
| 1920 |
-
calculations — no Python-level O(n_rec²) loops.
|
| 1921 |
"""
|
| 1922 |
import numpy as np
|
| 1923 |
from prody import parsePDB
|
|
@@ -1926,7 +1886,7 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 1926 |
if rec is None:
|
| 1927 |
return []
|
| 1928 |
|
| 1929 |
-
rc = np.array(rec.getCoords(), dtype=float)
|
| 1930 |
rrn = rec.getResnames()
|
| 1931 |
rch = rec.getChids()
|
| 1932 |
rri = rec.getResnums()
|
|
@@ -1942,26 +1902,22 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 1942 |
lel = [a.GetSymbol().upper() for a in latom]
|
| 1943 |
lchg = [a.GetFormalCharge() for a in latom]
|
| 1944 |
|
| 1945 |
-
# ── vdW radii ─────────────────────────────────────────────────────────────
|
| 1946 |
_VDW = {"H":1.20,"C":1.70,"N":1.55,"O":1.52,"S":1.80,"P":1.80,
|
| 1947 |
"F":1.47,"CL":1.75,"BR":1.85,"I":1.98,"SE":1.90}
|
| 1948 |
|
| 1949 |
-
# ── Pre-compute receptor element array ────────────────────────────────────
|
| 1950 |
nr = len(rc)
|
| 1951 |
r_el = [rel[j].strip().upper() if rel[j] and rel[j].strip()
|
| 1952 |
else ran[j][:1].upper() for j in range(nr)]
|
| 1953 |
-
r_el_arr = np.array(r_el)
|
| 1954 |
r_rn = np.array([rrn[j].strip() for j in range(nr)])
|
| 1955 |
r_an = np.array([ran[j].strip() for j in range(nr)])
|
| 1956 |
r_ch = np.array([rch[j].strip() for j in range(nr)])
|
| 1957 |
r_ri = np.array([int(rri[j]) for j in range(nr)])
|
| 1958 |
|
| 1959 |
-
# ── Pre-compute ligand element sets ───────────────────────────────────────
|
| 1960 |
HYDL = {"C","S","CL","BR","I","F"}
|
| 1961 |
-
HYDR = {"ALA","VAL","ILE","LEU","MET","PHE","TRP","PRO","GLY","TYR","HIS"}
|
| 1962 |
LIG_ACCEPTOR_EL = {"N","O","F","S"}
|
| 1963 |
|
| 1964 |
-
lig_is_acceptor
|
| 1965 |
lig_is_hydrophobic = np.array([lel[i] in HYDL for i in range(nl)])
|
| 1966 |
|
| 1967 |
def _is_lig_donor(i):
|
|
@@ -1973,45 +1929,35 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 1973 |
|
| 1974 |
lig_is_donor = np.array([_is_lig_donor(i) for i in range(nl)])
|
| 1975 |
|
| 1976 |
-
# ── Vectorised angle helper ───────────────────────────────────────────────
|
| 1977 |
def _angles_at_b(a_pts, b_pt, c_pt):
|
| 1978 |
-
|
| 1979 |
-
|
| 1980 |
-
|
| 1981 |
-
Returns (M,) array.
|
| 1982 |
-
"""
|
| 1983 |
-
va = a_pts - b_pt # (M,3)
|
| 1984 |
-
vc = c_pt - b_pt # (3,)
|
| 1985 |
-
na = np.linalg.norm(va, axis=1) # (M,)
|
| 1986 |
nc = float(np.linalg.norm(vc))
|
| 1987 |
if nc < 1e-8: return np.zeros(len(a_pts))
|
| 1988 |
-
cos_t = (va @ vc) / (na * nc + 1e-12)
|
| 1989 |
cos_t = np.clip(cos_t, -1.0, 1.0)
|
| 1990 |
return np.degrees(np.arccos(cos_t))
|
| 1991 |
|
| 1992 |
def _angle3(a, b, c):
|
| 1993 |
-
"""Scalar angle at b."""
|
| 1994 |
va = a - b; vc = c - b
|
| 1995 |
na = np.linalg.norm(va); nc = np.linalg.norm(vc)
|
| 1996 |
if na < 1e-8 or nc < 1e-8: return 0.0
|
| 1997 |
return float(np.degrees(np.arccos(
|
| 1998 |
np.clip(np.dot(va, vc) / (na * nc), -1.0, 1.0))))
|
| 1999 |
|
| 2000 |
-
# ── Build H→heavy and heavy→H maps (vectorised) ──────────────────────────
|
| 2001 |
h_mask = r_el_arr == "H"
|
| 2002 |
-
h_idx = np.where(h_mask)[0]
|
| 2003 |
-
heavy_idx = np.where(~h_mask)[0]
|
| 2004 |
|
| 2005 |
-
h_to_heavy = {}
|
| 2006 |
if len(h_idx) and len(heavy_idx):
|
| 2007 |
-
|
| 2008 |
-
|
| 2009 |
-
|
| 2010 |
-
|
| 2011 |
-
|
| 2012 |
-
|
| 2013 |
-
closest = np.argmin(dists_hh, axis=1) # (nH,)
|
| 2014 |
-
min_d = dists_hh[np.arange(len(h_idx)), closest]
|
| 2015 |
for k, (hi, ci, md) in enumerate(zip(h_idx, closest, min_d)):
|
| 2016 |
if md < 1.15:
|
| 2017 |
h_to_heavy[int(hi)] = int(heavy_idx[ci])
|
|
@@ -2020,7 +1966,6 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2020 |
for hj, hk in h_to_heavy.items():
|
| 2021 |
heavy_to_h.setdefault(hk, []).append(hj)
|
| 2022 |
|
| 2023 |
-
# ── HBD / HBA protein atom-name sets ─────────────────────────────────────
|
| 2024 |
PROT_DONOR_ATOMS = {
|
| 2025 |
"N","OG","OG1","OH","SG","NZ","NH1","NH2","NE",
|
| 2026 |
"ND1","NE2","NE1","ND2",
|
|
@@ -2034,14 +1979,10 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2034 |
HBOND_ANG_MIN = 120.0
|
| 2035 |
HBOND_PROXY = 90.0
|
| 2036 |
|
| 2037 |
-
results
|
| 2038 |
-
hbond_residues = set()
|
| 2039 |
-
|
| 2040 |
-
# ═══════════════════════════════════════════════════════════════════════════
|
| 2041 |
-
# H-BOND — iterate over donor/acceptor receptor atoms only
|
| 2042 |
-
# ═══════════════════════════════════════════════════════════════════════════
|
| 2043 |
|
| 2044 |
-
#
|
| 2045 |
polar_mask = np.array([
|
| 2046 |
r_el_arr[j] in ("N","O","S") and r_el_arr[j] != "H"
|
| 2047 |
and r_rn[j] not in ("HOH","WAT","DOD")
|
|
@@ -2056,10 +1997,8 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2056 |
if key in hbond_residues:
|
| 2057 |
continue
|
| 2058 |
|
| 2059 |
-
|
| 2060 |
-
dists_j = np.linalg.norm(lxyz - rp, axis=1) # (nl,)
|
| 2061 |
|
| 2062 |
-
# ── Case A: protein DONOR → ligand ACCEPTOR ───────────────────────────
|
| 2063 |
if an in PROT_DONOR_ATOMS:
|
| 2064 |
cand = np.where(lig_is_acceptor & (dists_j <= HBOND_DA_MAX))[0]
|
| 2065 |
if len(cand):
|
|
@@ -2067,21 +2006,11 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2067 |
for i in cand:
|
| 2068 |
d_DA = float(dists_j[i])
|
| 2069 |
if hs:
|
| 2070 |
-
h_coords_j = rc[np.array(hs)] # (nH,3)
|
| 2071 |
-
# D-H···A angle at H: vectors H→D and H→A
|
| 2072 |
-
angs = _angles_at_b(
|
| 2073 |
-
np.vstack([rp.reshape(1,3),
|
| 2074 |
-
lxyz[i].reshape(1,3)]),
|
| 2075 |
-
h_coords_j[0], # use first H
|
| 2076 |
-
lxyz[i] if len(hs)==1
|
| 2077 |
-
else lxyz[i])
|
| 2078 |
-
# Properly: angle at H between D and A
|
| 2079 |
best = max(
|
| 2080 |
_angle3(rp, rc[hj], lxyz[i]) for hj in hs
|
| 2081 |
)
|
| 2082 |
if best < HBOND_ANG_MIN: continue
|
| 2083 |
else:
|
| 2084 |
-
# Proxy: angle at A between D and any lig neighbour
|
| 2085 |
nbs_i = [nb.GetIdx() for nb in latom[i].GetNeighbors()
|
| 2086 |
if nb.GetAtomicNum() != 1 and nb.GetIdx() < nl]
|
| 2087 |
if nbs_i:
|
|
@@ -2095,13 +2024,11 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2095 |
|
| 2096 |
if key in hbond_residues: continue
|
| 2097 |
|
| 2098 |
-
# ── Case B: protein ACCEPTOR → ligand DONOR ───────────────────────────
|
| 2099 |
if an in PROT_ACCEPTOR_ATOMS:
|
| 2100 |
cand = np.where(lig_is_donor & (dists_j <= HBOND_DA_MAX))[0]
|
| 2101 |
if len(cand):
|
| 2102 |
for i in cand:
|
| 2103 |
d_DA = float(dists_j[i])
|
| 2104 |
-
# Ligand H atoms
|
| 2105 |
lig_hs = [nb.GetIdx() for nb in latom[i].GetNeighbors()
|
| 2106 |
if nb.GetAtomicNum() == 1 and nb.GetIdx() < nl]
|
| 2107 |
if lig_hs:
|
|
@@ -2120,16 +2047,15 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2120 |
prot_el=el,is_donor=False,ring_atom_indices=None))
|
| 2121 |
break
|
| 2122 |
|
| 2123 |
-
#
|
| 2124 |
-
# HYDROPHOBIC, IONIC, METAL (vectorised distance pre-filter)
|
| 2125 |
-
# ═══════════════════════════════════════════════════════════════════════════
|
| 2126 |
for j in range(nr):
|
| 2127 |
rn = r_rn[j]; ch = r_ch[j]; ri = int(r_ri[j]); el = r_el[j]; rp = rc[j]
|
| 2128 |
dists_j = np.linalg.norm(lxyz - rp, axis=1)
|
| 2129 |
md = float(dists_j.min()); mi = int(dists_j.argmin())
|
| 2130 |
if md > max(cutoff + 1.0, 5.6): continue
|
| 2131 |
|
| 2132 |
-
|
|
|
|
| 2133 |
cand = np.where(lig_is_hydrophobic & (dists_j < cutoff))[0]
|
| 2134 |
if len(cand):
|
| 2135 |
i = int(cand[0])
|
|
@@ -2150,15 +2076,15 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2150 |
itype="ionic",distance=round(float(dists_j[i]),1),
|
| 2151 |
lig_atom_idx=i,prot_el=el,is_donor=True,ring_atom_indices=None)); break
|
| 2152 |
|
| 2153 |
-
|
|
|
|
|
|
|
| 2154 |
if md < 2.8:
|
| 2155 |
results.append(dict(resname=rn,chain=ch,resid=ri,
|
| 2156 |
itype="metal",distance=round(md,1),lig_atom_idx=mi,
|
| 2157 |
prot_el=el,is_donor=False,ring_atom_indices=None))
|
| 2158 |
|
| 2159 |
-
#
|
| 2160 |
-
# π-π AND CATION-π
|
| 2161 |
-
# ═══════════════════════════════════════════════════════════════════════════
|
| 2162 |
lr = _get_aromatic_ring_data(lig_mol_3d, conf)
|
| 2163 |
if lr:
|
| 2164 |
arom_mask = np.array([
|
|
@@ -2188,13 +2114,10 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2188 |
lig_atom_idx=ring_idxs[0],prot_el="N",is_donor=True,
|
| 2189 |
ring_atom_indices=ring_idxs)); break
|
| 2190 |
|
| 2191 |
-
#
|
| 2192 |
-
# HALOGEN BOND C-X···A (vectorised acceptor search)
|
| 2193 |
-
# ═══════════════════════════════════════════════════════════════════════════
|
| 2194 |
_XD = {17:"CL", 35:"BR", 53:"I"}
|
| 2195 |
_XA_el = {"O","N","S","F"}
|
| 2196 |
|
| 2197 |
-
# Pre-build acceptor mask for receptor atoms
|
| 2198 |
arom_C_mask = np.array([
|
| 2199 |
r_rn[j] in _AROM_ATOMS and r_an[j] in _AROM_ATOM_NAMES and r_el[j] == "C"
|
| 2200 |
for j in range(nr)
|
|
@@ -2210,18 +2133,11 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2210 |
if c_nb is None: continue
|
| 2211 |
c_pos = lxyz[c_nb]
|
| 2212 |
|
| 2213 |
-
|
| 2214 |
-
max_d = vdw_x + 1.98 + 0.5 # use largest possible vdW(A)=I
|
| 2215 |
cand_mask = xb_acc_mask & (np.linalg.norm(rc - xp, axis=1) <= max_d)
|
| 2216 |
cand_idx = np.where(cand_mask)[0]
|
| 2217 |
if not len(cand_idx): continue
|
| 2218 |
|
| 2219 |
-
# Angle 1: C-X···A ≥ 140° (vectorised)
|
| 2220 |
-
ap_all = rc[cand_idx] # (M,3)
|
| 2221 |
-
ang1_all = _angles_at_b(
|
| 2222 |
-
np.vstack([c_pos.reshape(1,3)] * len(cand_idx)), # fake — use scalar
|
| 2223 |
-
xp, xp) # placeholder — compute properly below
|
| 2224 |
-
# scalar loop over candidates (already small after mask)
|
| 2225 |
for j in cand_idx:
|
| 2226 |
ael = r_el[j]; ap = rc[j]
|
| 2227 |
vdw_sum = vdw_x + _VDW.get(ael, 1.70) + 0.5
|
|
@@ -2229,7 +2145,6 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2229 |
if d > vdw_sum: continue
|
| 2230 |
ang1 = _angle3(c_pos, xp, ap)
|
| 2231 |
if ang1 < 140.0: continue
|
| 2232 |
-
# Angle 2: X···A-R ≥ 90°
|
| 2233 |
r_nbs = [k for k in range(nr)
|
| 2234 |
if k != j and r_el[k] != "H"
|
| 2235 |
and float(np.linalg.norm(rc[k] - ap)) < 1.85]
|
|
@@ -2239,14 +2154,12 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2239 |
itype="halogen",distance=round(d,1),lig_atom_idx=i,
|
| 2240 |
prot_el=ael,is_donor=False,ring_atom_indices=None))
|
| 2241 |
|
| 2242 |
-
#
|
| 2243 |
-
# H-BOND TO HALOGEN N/O-H···X (vectorised H search)
|
| 2244 |
-
# ═══════════════════════════════════════════════════════════════════════════
|
| 2245 |
_HA = {9:"F", 17:"CL", 35:"BR", 53:"I"}
|
| 2246 |
_HD = {"O","N","S"}
|
| 2247 |
|
| 2248 |
if len(h_idx):
|
| 2249 |
-
h_coords = rc[h_idx]
|
| 2250 |
for i in range(nl):
|
| 2251 |
ano = latom[i].GetAtomicNum()
|
| 2252 |
if ano not in _HA: continue
|
|
@@ -2255,8 +2168,7 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2255 |
if nb.GetIdx() < nl), None)
|
| 2256 |
if c_nb2 is None: continue
|
| 2257 |
c_pos2 = lxyz[c_nb2]
|
| 2258 |
-
|
| 2259 |
-
dhx_all = np.linalg.norm(h_coords - xp, axis=1) # (nH,)
|
| 2260 |
close_h = np.where(dhx_all <= _VDW["H"] + vdw_x)[0]
|
| 2261 |
for kk in close_h:
|
| 2262 |
hj = int(h_idx[kk]); hp = rc[hj]; dhx = float(dhx_all[kk])
|
|
@@ -2271,6 +2183,7 @@ def _detect_all_interactions(lig_mol_3d, receptor_pdb: str,
|
|
| 2271 |
|
| 2272 |
return results
|
| 2273 |
|
|
|
|
| 2274 |
def _deduplicate_interactions(interactions: list) -> list:
|
| 2275 |
priority={t:i for i,t in enumerate(_ITYPE_PRIORITY)}
|
| 2276 |
best:dict={}
|
|
@@ -2284,17 +2197,6 @@ def _deduplicate_interactions(interactions: list) -> list:
|
|
| 2284 |
|
| 2285 |
|
| 2286 |
def _enrich_with_res_xyz(interactions, mol3d, receptor_pdb):
|
| 2287 |
-
"""
|
| 2288 |
-
Add 'res_xyz' (3D position of the closest receptor atom) to each
|
| 2289 |
-
interaction dict in-place.
|
| 2290 |
-
|
| 2291 |
-
Must be called BEFORE lig_atom_idx is remapped from 3D→2D indices,
|
| 2292 |
-
because we need the original 3D ligand atom positions here.
|
| 2293 |
-
|
| 2294 |
-
For pi_pi / cation_pi interactions that reference a ring, we also
|
| 2295 |
-
store 'lig_xyz' (3D centroid of the ligand ring) so the PCA
|
| 2296 |
-
placement can use the true ring centre rather than a single atom.
|
| 2297 |
-
"""
|
| 2298 |
import numpy as np
|
| 2299 |
from prody import parsePDB
|
| 2300 |
try:
|
|
@@ -2317,8 +2219,6 @@ def _enrich_with_res_xyz(interactions, mol3d, receptor_pdb):
|
|
| 2317 |
lai = ix.get("lig_atom_idx", 0)
|
| 2318 |
lai = min(lai, n_lig - 1)
|
| 2319 |
|
| 2320 |
-
# --- Ligand-side 3D anchor -----------------------------------------
|
| 2321 |
-
# For pi_pi/cation_pi: use the ring centroid if ring indices available
|
| 2322 |
ring_idxs = ix.get("ring_atom_indices") or []
|
| 2323 |
if ring_idxs:
|
| 2324 |
valid = [i for i in ring_idxs if 0 <= i < n_lig]
|
|
@@ -2330,16 +2230,12 @@ def _enrich_with_res_xyz(interactions, mol3d, receptor_pdb):
|
|
| 2330 |
lig_anchor = lxyz[lai]
|
| 2331 |
ix["lig_anchor_xyz"] = lig_anchor.tolist()
|
| 2332 |
|
| 2333 |
-
# --- Receptor-side 3D anchor ----------------------------------------
|
| 2334 |
-
# Find all atoms belonging to this residue
|
| 2335 |
res_idx = [j for j in range(len(rc))
|
| 2336 |
if rch[j].strip() == ch and int(rri[j]) == ri]
|
| 2337 |
if not res_idx:
|
| 2338 |
-
ix["res_xyz"] = lig_anchor.tolist()
|
| 2339 |
continue
|
| 2340 |
|
| 2341 |
-
# For aromatic interactions (pi_pi / cation_pi): prefer the ring-atom
|
| 2342 |
-
# subset of this residue if available (gives a more centroid-like point)
|
| 2343 |
res_coords = rc[res_idx]
|
| 2344 |
dists = np.linalg.norm(res_coords - lig_anchor, axis=1)
|
| 2345 |
closest_local = int(dists.argmin())
|
|
@@ -2359,7 +2255,6 @@ def _compute_svg_coords(mol2d, cx, cy, target_size=280):
|
|
| 2359 |
|
| 2360 |
|
| 2361 |
def _ring_centroid_2d(ring_atom_indices, svg_coords):
|
| 2362 |
-
"""Compute 2D centroid of an aromatic ring from SVG coordinates."""
|
| 2363 |
xs=[svg_coords[i][0] for i in ring_atom_indices if i in svg_coords]
|
| 2364 |
ys=[svg_coords[i][1] for i in ring_atom_indices if i in svg_coords]
|
| 2365 |
if not xs: return None, None
|
|
@@ -2367,20 +2262,11 @@ def _ring_centroid_2d(ring_atom_indices, svg_coords):
|
|
| 2367 |
|
| 2368 |
|
| 2369 |
def _ring_centroid_from_atom(mol2d, atom_idx_2d, svg_coords):
|
| 2370 |
-
"""
|
| 2371 |
-
Find the aromatic ring in mol2d that contains atom_idx_2d, then
|
| 2372 |
-
return its 2D SVG centroid.
|
| 2373 |
-
|
| 2374 |
-
This avoids the fragile 3D→2D ring_atom_indices remapping (which breaks
|
| 2375 |
-
when mol3d has explicit Hs, shifting heavy-atom indices relative to m3).
|
| 2376 |
-
Falls back to (None, None) if atom is not in any aromatic ring.
|
| 2377 |
-
"""
|
| 2378 |
ring_info = mol2d.GetRingInfo()
|
| 2379 |
best_ring = None
|
| 2380 |
best_size = 999
|
| 2381 |
for ring in ring_info.AtomRings():
|
| 2382 |
if atom_idx_2d in ring:
|
| 2383 |
-
# Prefer 6-membered rings; among ties pick first found
|
| 2384 |
if mol2d.GetAtomWithIdx(ring[0]).GetIsAromatic():
|
| 2385 |
if len(ring) < best_size:
|
| 2386 |
best_ring = ring
|
|
@@ -2395,21 +2281,8 @@ def _ring_centroid_from_atom(mol2d, atom_idx_2d, svg_coords):
|
|
| 2395 |
|
| 2396 |
|
| 2397 |
def _place_residues_no_cross(interactions, svg_coords, cx, cy, R=210):
|
| 2398 |
-
"""
|
| 2399 |
-
Place residue labels at their natural ligand-atom direction, then
|
| 2400 |
-
push overlapping labels apart using simultaneous delta updates.
|
| 2401 |
-
|
| 2402 |
-
Key fixes vs previous version:
|
| 2403 |
-
- Simultaneous delta accumulation (no in-place sequential mutation
|
| 2404 |
-
that caused oscillation and non-convergence)
|
| 2405 |
-
- All-pairs O(n²) check based on actual pixel distance (not just
|
| 2406 |
-
adjacent-pair angular gap, which misses non-adjacent overlaps)
|
| 2407 |
-
- min_dist based on true label bounding box (text width + circle r)
|
| 2408 |
-
- Preserves angular sort order → lines never cross
|
| 2409 |
-
"""
|
| 2410 |
if not interactions: return []
|
| 2411 |
|
| 2412 |
-
# 1. Compute natural angle for each residue
|
| 2413 |
items = []
|
| 2414 |
for ix in interactions:
|
| 2415 |
if ix.get("ring_atom_indices"):
|
|
@@ -2422,7 +2295,6 @@ def _place_residues_no_cross(interactions, svg_coords, cx, cy, R=210):
|
|
| 2422 |
angle = _math.atan2(ay - cy, ax - cx)
|
| 2423 |
items.append({**ix, "angle": angle, "anchor_angle": angle})
|
| 2424 |
|
| 2425 |
-
# 2. Sort by natural angle → preserving this order prevents line crossings
|
| 2426 |
items.sort(key=lambda x: x["angle"])
|
| 2427 |
n = len(items)
|
| 2428 |
if n == 1:
|
|
@@ -2432,22 +2304,13 @@ def _place_residues_no_cross(interactions, svg_coords, cx, cy, R=210):
|
|
| 2432 |
"by": cy + R * _math.sin(a),
|
| 2433 |
"slot_angle": a}]
|
| 2434 |
|
| 2435 |
-
# 3. Break ties: items sharing the same anchor angle start at distance=0
|
| 2436 |
-
# and the push loop can never separate them. Add a tiny jitter so each
|
| 2437 |
-
# gets a unique starting angle before the push loop runs.
|
| 2438 |
for i in range(n):
|
| 2439 |
for j in range(i + 1, n):
|
| 2440 |
if abs(items[j]["angle"] - items[i]["angle"]) < 0.001:
|
| 2441 |
-
items[j]["angle"] += 0.05 * (j - i)
|
| 2442 |
|
| 2443 |
-
# 4. Minimum pixel distance between label centers.
|
| 2444 |
-
# "MET 769A" = 8 chars × ~8.5px = 68px + circle r 24.55 on each side.
|
| 2445 |
-
# Effective min = text_width + 2*circle_r + margin ≈ 78px.
|
| 2446 |
min_dist_px = 78.0
|
| 2447 |
|
| 2448 |
-
# 5. Simultaneous-delta push-apart — O(n²) all-pairs, 500 iterations.
|
| 2449 |
-
# Key: accumulate ALL deltas before applying so sequential pairs
|
| 2450 |
-
# don't contaminate each other within one pass.
|
| 2451 |
for _ in range(500):
|
| 2452 |
delta = [0.0] * n
|
| 2453 |
any_overlap = False
|
|
@@ -2463,10 +2326,7 @@ def _place_residues_no_cross(interactions, svg_coords, cx, cy, R=210):
|
|
| 2463 |
|
| 2464 |
if dist < min_dist_px:
|
| 2465 |
overlap_px = min_dist_px - dist
|
| 2466 |
-
# Convert pixel overlap to angular push (chord ≈ arc for small angles)
|
| 2467 |
push_angle = overlap_px / max(R, 1.0)
|
| 2468 |
-
# Always push i counter-clockwise and j clockwise relative to sorted order
|
| 2469 |
-
# (sorted order is guaranteed by step 2, so i always precedes j)
|
| 2470 |
delta[i] -= push_angle * 0.5
|
| 2471 |
delta[j] += push_angle * 0.5
|
| 2472 |
any_overlap = True
|
|
@@ -2477,7 +2337,6 @@ def _place_residues_no_cross(interactions, svg_coords, cx, cy, R=210):
|
|
| 2477 |
if not any_overlap:
|
| 2478 |
break
|
| 2479 |
|
| 2480 |
-
# 5. Final clamp: keep all labels within canvas bounds
|
| 2481 |
result = []
|
| 2482 |
for item in items:
|
| 2483 |
a = item["angle"]
|
|
@@ -2492,17 +2351,9 @@ def _place_residues_no_cross(interactions, svg_coords, cx, cy, R=210):
|
|
| 2492 |
return result
|
| 2493 |
|
| 2494 |
|
| 2495 |
-
|
| 2496 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 2497 |
-
# RADIAL-COLLAPSE LAYOUT — modular helper functions
|
| 2498 |
-
# Called by _place_residues_pca (main entry point at the end of this block).
|
| 2499 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 2500 |
|
| 2501 |
def _rl_ligand_center(svg_coords):
|
| 2502 |
-
"""
|
| 2503 |
-
Return (cx, cy): centroid of all 2D ligand atom SVG positions.
|
| 2504 |
-
Used as the origin for every radial direction calculation.
|
| 2505 |
-
"""
|
| 2506 |
pts = list(svg_coords.values())
|
| 2507 |
if not pts:
|
| 2508 |
return 400.0, 380.0
|
|
@@ -2512,14 +2363,6 @@ def _rl_ligand_center(svg_coords):
|
|
| 2512 |
|
| 2513 |
|
| 2514 |
def _rl_anchor_angle(ix, svg_coords, cx, cy):
|
| 2515 |
-
"""
|
| 2516 |
-
Return the anchor angle θ (radians) for one interaction.
|
| 2517 |
-
|
| 2518 |
-
The anchor is the SVG position of the ligand atom (or aromatic ring
|
| 2519 |
-
centroid) that the interaction line is drawn from. The angle is measured
|
| 2520 |
-
from the ligand centroid (cx, cy) so that it defines the radial direction
|
| 2521 |
-
along which the residue label will be placed.
|
| 2522 |
-
"""
|
| 2523 |
ai = ix.get("lig_atom_idx", 0)
|
| 2524 |
ax, ay = svg_coords.get(ai, (cx, cy))
|
| 2525 |
ring_idxs = ix.get("ring_atom_indices")
|
|
@@ -2531,28 +2374,6 @@ def _rl_anchor_angle(ix, svg_coords, cx, cy):
|
|
| 2531 |
|
| 2532 |
|
| 2533 |
def _rl_ray_boundary(cx, cy, theta, atom_xy, atom_r=20.0):
|
| 2534 |
-
"""
|
| 2535 |
-
Cast a ray from the ligand centroid (cx, cy) in direction theta and
|
| 2536 |
-
return the distance to the far edge of the ligand's union-of-circles
|
| 2537 |
-
boundary model.
|
| 2538 |
-
|
| 2539 |
-
Ligand boundary model
|
| 2540 |
-
─────────────────────
|
| 2541 |
-
Each ligand heavy atom is modelled as a circle of radius atom_r (px).
|
| 2542 |
-
The ligand boundary at angle theta is the farthest exit point t_exit
|
| 2543 |
-
of the ray through any of those circles.
|
| 2544 |
-
|
| 2545 |
-
For atom at (ax, ay):
|
| 2546 |
-
v = (ax-cx, ay-cy)
|
| 2547 |
-
t_c = v · d̂ (projection onto ray)
|
| 2548 |
-
perp² = |v|² − t_c² (squared perpendicular distance to ray)
|
| 2549 |
-
if perp² < atom_r²:
|
| 2550 |
-
t_exit = t_c + √(atom_r² − perp²)
|
| 2551 |
-
boundary = max(boundary, t_exit)
|
| 2552 |
-
|
| 2553 |
-
Returns a fallback distance of 20 px if no atom is intersected
|
| 2554 |
-
(can happen for rays pointing away from the ligand).
|
| 2555 |
-
"""
|
| 2556 |
dx = _math.cos(theta)
|
| 2557 |
dy = _math.sin(theta)
|
| 2558 |
r2 = atom_r * atom_r
|
|
@@ -2561,41 +2382,22 @@ def _rl_ray_boundary(cx, cy, theta, atom_xy, atom_r=20.0):
|
|
| 2561 |
vx = ax - cx
|
| 2562 |
vy = ay - cy
|
| 2563 |
t_proj = vx * dx + vy * dy
|
| 2564 |
-
if t_proj < -atom_r:
|
| 2565 |
continue
|
| 2566 |
perp2 = vx * vx + vy * vy - t_proj * t_proj
|
| 2567 |
-
if perp2 >= r2:
|
| 2568 |
continue
|
| 2569 |
t_exit = t_proj + _math.sqrt(max(r2 - perp2, 0.0))
|
| 2570 |
if t_exit > t_max:
|
| 2571 |
t_max = t_exit
|
| 2572 |
-
return t_max if t_max > 1.0 else 20.0
|
| 2573 |
|
| 2574 |
|
| 2575 |
def _rl_place_radially(sorted_interactions, svg_coords, cx, cy,
|
| 2576 |
atom_xy, atom_r, gap, node_r, rng):
|
| 2577 |
-
|
| 2578 |
-
|
| 2579 |
-
|
| 2580 |
-
For each interaction (pre-sorted by anchor angle for non-crossing order):
|
| 2581 |
-
1. Compute anchor angle θ from ligand centroid.
|
| 2582 |
-
2. Ray-cast the ligand boundary at θ → distance d_boundary.
|
| 2583 |
-
3. Place the circle centre at:
|
| 2584 |
-
r_place = d_boundary + gap + node_r
|
| 2585 |
-
along direction θ, plus a small deterministic jitter to prevent
|
| 2586 |
-
perfectly collinear labels (tangential ±7 px, radial ±4 px).
|
| 2587 |
-
|
| 2588 |
-
The jitter is derived from each interaction's sorted rank so the layout
|
| 2589 |
-
is fully reproducible (same result every call for the same molecule).
|
| 2590 |
-
|
| 2591 |
-
Returns
|
| 2592 |
-
-------
|
| 2593 |
-
positions : list of (bx, by) floats, one per interaction in input order.
|
| 2594 |
-
"""
|
| 2595 |
-
JITTER_T = 7.0 # max tangential jitter (px) — perpendicular to ray
|
| 2596 |
-
JITTER_R = 4.0 # max radial jitter (px) — along ray
|
| 2597 |
|
| 2598 |
-
# Pre-draw all jitter values from the seeded rng for reproducibility
|
| 2599 |
n = len(sorted_interactions)
|
| 2600 |
jit_t = rng.uniform(-JITTER_T, JITTER_T, n)
|
| 2601 |
jit_r = rng.uniform(-JITTER_R, JITTER_R, n)
|
|
@@ -2608,7 +2410,6 @@ def _rl_place_radially(sorted_interactions, svg_coords, cx, cy,
|
|
| 2608 |
|
| 2609 |
cos_t = _math.cos(theta)
|
| 2610 |
sin_t = _math.sin(theta)
|
| 2611 |
-
# Tangential unit vector (rotate 90° CCW from radial)
|
| 2612 |
tx, ty = -sin_t, cos_t
|
| 2613 |
|
| 2614 |
bx = cx + r_place * cos_t + jit_t[k] * tx
|
|
@@ -2620,49 +2421,15 @@ def _rl_place_radially(sorted_interactions, svg_coords, cx, cy,
|
|
| 2620 |
|
| 2621 |
def _rl_resolve_overlaps(positions, atom_xy, cx, cy,
|
| 2622 |
node_r=24.55, excl_r=46.0, max_iters=400):
|
| 2623 |
-
"""
|
| 2624 |
-
Resolve residue-circle overlaps using simultaneous-delta push-apart,
|
| 2625 |
-
with a secondary ligand-exclusion step.
|
| 2626 |
-
|
| 2627 |
-
Two forces are applied each iteration:
|
| 2628 |
-
─ Node–node repulsion (simultaneous delta)
|
| 2629 |
-
For each pair (i,j) whose centres are closer than min_sep:
|
| 2630 |
-
push both apart along the connecting vector.
|
| 2631 |
-
Δ is accumulated for all pairs before being applied
|
| 2632 |
-
(prevents sequential contamination / oscillation).
|
| 2633 |
-
|
| 2634 |
-
─ Ligand-exclusion (sequential, applied after repulsion)
|
| 2635 |
-
For each node closer than excl_r to any ligand atom centre:
|
| 2636 |
-
push the node outward along the connecting vector.
|
| 2637 |
-
|
| 2638 |
-
The push-apart operates in full 2D Cartesian space so that labels can
|
| 2639 |
-
drift slightly in the tangential direction, producing the natural
|
| 2640 |
-
non-uniform scatter seen in publication diagrams.
|
| 2641 |
-
|
| 2642 |
-
Parameters
|
| 2643 |
-
----------
|
| 2644 |
-
positions : list of (bx, by)
|
| 2645 |
-
atom_xy : list of (ax, ay) for ligand atoms (exclusion boundary)
|
| 2646 |
-
cx, cy : ligand centroid (fallback push direction if overlap is zero)
|
| 2647 |
-
node_r : residue circle radius (px)
|
| 2648 |
-
excl_r : min distance from node centre to any ligand atom centre
|
| 2649 |
-
max_iters : iteration cap
|
| 2650 |
-
|
| 2651 |
-
Returns
|
| 2652 |
-
-------
|
| 2653 |
-
new list of (bx, by)
|
| 2654 |
-
"""
|
| 2655 |
n = len(positions)
|
| 2656 |
if n <= 1:
|
| 2657 |
return list(positions)
|
| 2658 |
|
| 2659 |
-
min_sep = node_r * 2.0 + 8.0
|
| 2660 |
|
| 2661 |
bx = [p[0] for p in positions]
|
| 2662 |
by = [p[1] for p in positions]
|
| 2663 |
|
| 2664 |
-
# Pre-pass: separate exactly-coincident (or near-coincident) nodes by a
|
| 2665 |
-
# tiny golden-angle kick so the main loop has a direction to work with.
|
| 2666 |
for i in range(n):
|
| 2667 |
for j in range(i + 1, n):
|
| 2668 |
ddx = bx[j] - bx[i]; ddy = by[j] - by[i]
|
|
@@ -2673,7 +2440,6 @@ def _rl_resolve_overlaps(positions, atom_xy, cx, cy,
|
|
| 2673 |
bx[j] += _math.cos(ang) * kick; by[j] += _math.sin(ang) * kick
|
| 2674 |
|
| 2675 |
for _it in range(max_iters):
|
| 2676 |
-
# ── Node–node repulsion (simultaneous delta) ────────────────��─────
|
| 2677 |
dx_acc = [0.0] * n
|
| 2678 |
dy_acc = [0.0] * n
|
| 2679 |
any_overlap = False
|
|
@@ -2693,7 +2459,6 @@ def _rl_resolve_overlaps(positions, atom_xy, cx, cy,
|
|
| 2693 |
bx[i] += dx_acc[i]
|
| 2694 |
by[i] += dy_acc[i]
|
| 2695 |
|
| 2696 |
-
# ── Ligand-exclusion (sequential push outward from each atom) ─────
|
| 2697 |
for i in range(n):
|
| 2698 |
for (ax, ay) in atom_xy:
|
| 2699 |
ddx = bx[i] - ax
|
|
@@ -2701,7 +2466,6 @@ def _rl_resolve_overlaps(positions, atom_xy, cx, cy,
|
|
| 2701 |
d = _math.sqrt(ddx * ddx + ddy * ddy) + 1e-8
|
| 2702 |
if d < excl_r:
|
| 2703 |
push = (excl_r - d) * 0.5 / d
|
| 2704 |
-
# If node is exactly on atom centre, push radially outward
|
| 2705 |
if d < 0.5:
|
| 2706 |
ddx = bx[i] - cx
|
| 2707 |
ddy = by[i] - cy
|
|
@@ -2717,20 +2481,6 @@ def _rl_resolve_overlaps(positions, atom_xy, cx, cy,
|
|
| 2717 |
|
| 2718 |
|
| 2719 |
def _rl_reduce_crossings(ix_list, bx_by, svg_coords, cx, cy):
|
| 2720 |
-
"""
|
| 2721 |
-
Minimise interaction-line crossings by iterative pair-swap.
|
| 2722 |
-
|
| 2723 |
-
For every pair (i, j) whose lines anchor_i→node_i and anchor_j→node_j
|
| 2724 |
-
properly intersect, swap the two node positions. A swap eliminates
|
| 2725 |
-
the crossing between pair (i,j) and cannot introduce a new crossing
|
| 2726 |
-
between the same pair.
|
| 2727 |
-
|
| 2728 |
-
Iterates until no crossing pair remains or n·2 passes are exhausted.
|
| 2729 |
-
|
| 2730 |
-
Returns
|
| 2731 |
-
-------
|
| 2732 |
-
bx_by : new list of (bx, by) with minimised crossing count.
|
| 2733 |
-
"""
|
| 2734 |
n = len(ix_list)
|
| 2735 |
bx_by = list(bx_by)
|
| 2736 |
|
|
@@ -2745,7 +2495,6 @@ def _rl_reduce_crossings(ix_list, bx_by, svg_coords, cx, cy):
|
|
| 2745 |
return (ax, ay)
|
| 2746 |
|
| 2747 |
def _cross(a1, b1, a2, b2):
|
| 2748 |
-
"""True if segment a1→b1 properly intersects segment a2→b2."""
|
| 2749 |
def _side(O, A, B):
|
| 2750 |
return (B[0]-O[0])*(A[1]-O[1]) - (B[1]-O[1])*(A[0]-O[0])
|
| 2751 |
d1 = _side(a2, b2, a1); d2 = _side(a2, b2, b1)
|
|
@@ -2767,95 +2516,41 @@ def _rl_reduce_crossings(ix_list, bx_by, svg_coords, cx, cy):
|
|
| 2767 |
|
| 2768 |
|
| 2769 |
def _place_residues_pca(interactions, svg_coords, mol3d, cx, cy, R=210):
|
| 2770 |
-
"""
|
| 2771 |
-
Radial-collapse layout: residue circles placed just outside the drawn
|
| 2772 |
-
ligand boundary, in the direction of their interaction anchor.
|
| 2773 |
-
|
| 2774 |
-
Five-step algorithm
|
| 2775 |
-
───────────────────
|
| 2776 |
-
1. Ligand centroid + boundary model
|
| 2777 |
-
Compute the geometric centroid of all 2D ligand atom positions.
|
| 2778 |
-
Model the ligand boundary as the union of per-atom circles
|
| 2779 |
-
(radius atom_r ≈ 20 px), enabling direction-specific surface
|
| 2780 |
-
distance estimation via ray casting.
|
| 2781 |
-
|
| 2782 |
-
2. Anchor angles + angular sort
|
| 2783 |
-
For each interaction, compute the angle from the ligand centroid to
|
| 2784 |
-
its anchor atom (or ring centroid for π-interactions).
|
| 2785 |
-
Sort interactions by this angle → circular order invariant that
|
| 2786 |
-
guarantees non-crossing lines when node positions preserve the order.
|
| 2787 |
-
|
| 2788 |
-
3. Initial radial placement
|
| 2789 |
-
For each (sorted) residue:
|
| 2790 |
-
r = ray_boundary(θ) + gap + node_r + small_jitter
|
| 2791 |
-
Nodes are placed outward from the ligand surface along the anchor
|
| 2792 |
-
direction, at varying distances that reflect the actual ligand shape.
|
| 2793 |
-
|
| 2794 |
-
4. Overlap resolution
|
| 2795 |
-
Simultaneous-delta push-apart (2D Cartesian) + ligand-exclusion
|
| 2796 |
-
to ensure no two circles overlap and none overlaps the ligand.
|
| 2797 |
-
|
| 2798 |
-
5. Crossing reduction
|
| 2799 |
-
Swap-based pairwise crossing elimination on the interaction lines.
|
| 2800 |
-
|
| 2801 |
-
Parameters
|
| 2802 |
-
----------
|
| 2803 |
-
interactions : list of interaction dicts (after deduplication)
|
| 2804 |
-
svg_coords : {atom_idx: (x_svg, y_svg)} for the 2D ligand
|
| 2805 |
-
mol3d : RDKit molecule with 3D conformer (kept for API compat;
|
| 2806 |
-
not used — placement is entirely from 2D geometry)
|
| 2807 |
-
cx, cy : canvas centre (fallback if svg_coords is empty)
|
| 2808 |
-
R : reference ring radius (used only by the fallback)
|
| 2809 |
-
|
| 2810 |
-
Returns
|
| 2811 |
-
-------
|
| 2812 |
-
list of placement dicts, each with keys:
|
| 2813 |
-
bx, by — residue circle centre in SVG pixels
|
| 2814 |
-
angle — angle from ligand centroid to circle centre
|
| 2815 |
-
slot_angle — same (alias kept for renderer compatibility)
|
| 2816 |
-
+ all keys from the original interaction dict
|
| 2817 |
-
"""
|
| 2818 |
if not interactions:
|
| 2819 |
return []
|
| 2820 |
|
| 2821 |
try:
|
| 2822 |
import numpy as _np_rc
|
| 2823 |
|
| 2824 |
-
NODE_R = 24.55
|
| 2825 |
-
GAP = 45.0
|
| 2826 |
-
ATOM_R = 20.0
|
| 2827 |
|
| 2828 |
-
# ── Step 1: Ligand centroid + atom positions ───────────────────────
|
| 2829 |
lx, ly = _rl_ligand_center(svg_coords)
|
| 2830 |
atom_xy = list(svg_coords.values())
|
| 2831 |
|
| 2832 |
-
# ── Step 2: Anchor angles + sort ──────────────────────────────────
|
| 2833 |
anchor_a = [_rl_anchor_angle(ix, svg_coords, lx, ly)
|
| 2834 |
for ix in interactions]
|
| 2835 |
order = sorted(range(len(interactions)),
|
| 2836 |
key=lambda k: anchor_a[k])
|
| 2837 |
sorted_ix = [interactions[k] for k in order]
|
| 2838 |
|
| 2839 |
-
# ── Step 3: Initial radial placement ──────────────────────────────
|
| 2840 |
rng = _np_rc.random.default_rng(42)
|
| 2841 |
positions = _rl_place_radially(
|
| 2842 |
sorted_ix, svg_coords, lx, ly,
|
| 2843 |
atom_xy, ATOM_R, GAP, NODE_R, rng,
|
| 2844 |
)
|
| 2845 |
|
| 2846 |
-
# ── Step 4: Overlap resolution ────────────────────────────────────
|
| 2847 |
positions = _rl_resolve_overlaps(
|
| 2848 |
positions, atom_xy, lx, ly,
|
| 2849 |
node_r=NODE_R,
|
| 2850 |
-
excl_r=NODE_R + ATOM_R,
|
| 2851 |
)
|
| 2852 |
|
| 2853 |
-
# ── Step 5: Crossing reduction ────────────────────────────────────
|
| 2854 |
positions = _rl_reduce_crossings(
|
| 2855 |
sorted_ix, positions, svg_coords, lx, ly,
|
| 2856 |
)
|
| 2857 |
|
| 2858 |
-
# ── Build output ──────────────────────────────────────────────────
|
| 2859 |
result = []
|
| 2860 |
for k, (bx, by) in enumerate(positions):
|
| 2861 |
ang = _math.atan2(by - ly, bx - lx)
|
|
@@ -2871,6 +2566,7 @@ def _place_residues_pca(interactions, svg_coords, mol3d, cx, cy, R=210):
|
|
| 2871 |
except Exception:
|
| 2872 |
return _place_residues_no_cross(interactions, svg_coords, cx, cy, R)
|
| 2873 |
|
|
|
|
| 2874 |
def _render_ligand_svg(mol2d, svg_coords):
|
| 2875 |
from rdkit import Chem
|
| 2876 |
parts=[]
|
|
@@ -2901,7 +2597,7 @@ def _render_ligand_svg(mol2d, svg_coords):
|
|
| 2901 |
f' stroke="#1a1a1a" stroke-width="1.77" opacity="0.9"/>')
|
| 2902 |
elif bt==Chem.BondType.DOUBLE:
|
| 2903 |
dx,dy=x2s-x1s,y2s-y1s; L=_math.sqrt(dx*dx+dy*dy)+1e-9
|
| 2904 |
-
px,py=-dy/L*2.5,dx/L*2.5
|
| 2905 |
for sg in (1,-1):
|
| 2906 |
parts.append(f'<line x1="{x1s+px*sg:.2f}" y1="{y1s+py*sg:.2f}"'
|
| 2907 |
f' x2="{x2s+px*sg:.2f}" y2="{y2s+py*sg:.2f}"'
|
|
@@ -2917,7 +2613,7 @@ def _render_ligand_svg(mol2d, svg_coords):
|
|
| 2917 |
bd=bond.GetBondDir()
|
| 2918 |
if bd==Chem.BondDir.BEGINWEDGE:
|
| 2919 |
dx,dy=x2s-x1s,y2s-y1s; L=_math.sqrt(dx*dx+dy*dy)+1e-9
|
| 2920 |
-
px,py=-dy/L*3.0,dx/L*3.0
|
| 2921 |
parts.append(f'<polygon points="{x1s:.2f},{y1s:.2f}'
|
| 2922 |
f' {x2s+px:.2f},{y2s+py:.2f} {x2s-px:.2f},{y2s-py:.2f}"'
|
| 2923 |
f' fill="#1a1a1a" stroke="none"/>')
|
|
@@ -2933,7 +2629,6 @@ def _render_ligand_svg(mol2d, svg_coords):
|
|
| 2933 |
parts.append(f'<line x1="{x1s:.2f}" y1="{y1s:.2f}" x2="{x2s:.2f}" y2="{y2s:.2f}"'
|
| 2934 |
f' stroke="#1a1a1a" stroke-width="1.77" opacity="0.9"/>')
|
| 2935 |
|
| 2936 |
-
# Aromatic: dashed circle (st14) + green dot (st18)
|
| 2937 |
for ring in arom_rings:
|
| 2938 |
rcoords=[svg_coords.get(i,(0,0)) for i in ring]
|
| 2939 |
rcx=sum(x for x,y in rcoords)/len(rcoords)
|
|
@@ -2946,13 +2641,12 @@ def _render_ligand_svg(mol2d, svg_coords):
|
|
| 2946 |
parts.append(f'<circle cx="{rcx:.2f}" cy="{rcy:.2f}" r="5.43"'
|
| 2947 |
f' fill="{_AROM_DOT_CLR}"/>')
|
| 2948 |
|
| 2949 |
-
# Heteroatom labels: white bg rect + colored bold text (no circle border)
|
| 2950 |
for i in range(mol2d.GetNumAtoms()):
|
| 2951 |
atom=mol2d.GetAtomWithIdx(i); sym=atom.GetSymbol()
|
| 2952 |
if sym=="C": continue
|
| 2953 |
ax,ay=svg_coords.get(i,(0,0))
|
| 2954 |
clr=_ATOM_CLR.get(sym.upper(),"#555")
|
| 2955 |
-
fs={"H":16}.get(sym,17.65)
|
| 2956 |
hw={"H":7,"N":9,"O":9,"S":11,"P":11,"F":8,"CL":16,"BR":16,"I":11}.get(sym.upper(),9)
|
| 2957 |
parts.append(f'<rect x="{ax-hw:.1f}" y="{ay-11:.1f}"'
|
| 2958 |
f' width="{hw*2:.0f}" height="22" fill="white" stroke="none"/>')
|
|
@@ -2969,16 +2663,11 @@ def _render_ligand_svg(mol2d, svg_coords):
|
|
| 2969 |
return "".join(parts)
|
| 2970 |
|
| 2971 |
|
| 2972 |
-
# ──────────────────────────────────────────────────────────────────────────────
|
| 2973 |
-
# MAIN SVG RENDERER
|
| 2974 |
-
# ──────────────────────────────────────────────────────────────────────────────
|
| 2975 |
-
|
| 2976 |
def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
| 2977 |
parts=[]
|
| 2978 |
parts.append(f'<svg width="100%" viewBox="0 0 {W} {H}" xmlns="http://www.w3.org/2000/svg">')
|
| 2979 |
parts.append(f'<rect width="{W}" height="{H}" fill="white"/>')
|
| 2980 |
|
| 2981 |
-
# ── Title pill: st19 fill #f2f2f2, st7 font 24.93px bold ─────────────────
|
| 2982 |
if title:
|
| 2983 |
esc=title.replace("&","&").replace("<","<").replace(">",">")
|
| 2984 |
tw=len(esc)*14.5+48; tw=max(tw,240); tw=min(tw,W-40)
|
|
@@ -2990,7 +2679,6 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 2990 |
f' font-family="Arial,sans-serif" font-size="24.93"'
|
| 2991 |
f' font-weight="700" fill="#1a1a1a">{esc}</text>')
|
| 2992 |
|
| 2993 |
-
# ── PASS 1: Residue background circles (drawn first — behind lines) ───────
|
| 2994 |
for p in placements:
|
| 2995 |
itype=p["itype"]
|
| 2996 |
bx,by=p["bx"],p["by"]
|
|
@@ -2999,15 +2687,13 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 2999 |
parts.append(f'<circle cx="{cbx:.1f}" cy="{cby:.1f}" r="24.55"'
|
| 3000 |
f' fill="{bg["fill"]}" opacity="{bg["opacity"]}"/>')
|
| 3001 |
|
| 3002 |
-
# ── PASS 2: Interaction lines ─────────────────────────────────────────────
|
| 3003 |
for p in placements:
|
| 3004 |
itype=p["itype"]
|
| 3005 |
-
if itype=="hydrophobic": continue
|
| 3006 |
|
| 3007 |
bx,by=p["bx"],p["by"]
|
| 3008 |
cbx=max(50,min(bx,W-50)); cby=max(70,min(by,H-65))
|
| 3009 |
|
| 3010 |
-
# Line start: ring centroid for π-π, else ligand atom position
|
| 3011 |
if itype in ("pi_pi","cation_pi") and p.get("ring_atom_indices"):
|
| 3012 |
lx,ly=_ring_centroid_2d(p["ring_atom_indices"],svg_coords)
|
| 3013 |
if lx is None:
|
|
@@ -3020,30 +2706,23 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 3020 |
dash_attr_hbx=' stroke-dasharray="4 2 1 2"'
|
| 3021 |
|
| 3022 |
if itype in ("pi_pi","cation_pi"):
|
| 3023 |
-
# st5: stroke #e200e8, dasharray "5 3", stroke-width 1.6, opacity 0.85
|
| 3024 |
parts.append(f'<line x1="{lx:.2f}" y1="{ly:.2f}"'
|
| 3025 |
f' x2="{cbx:.2f}" y2="{cby:.2f}"'
|
| 3026 |
f' stroke="{clr}" stroke-width="1.6"'
|
| 3027 |
f'{dash_attr} opacity="0.85"/>')
|
| 3028 |
elif itype in ("hbond","hbond_to_halogen"):
|
| 3029 |
-
# st13: stroke #1a7a1a, dasharray "5 3", stroke-width 1.6, opacity 0.85
|
| 3030 |
da=dash_attr if itype=="hbond" else dash_attr_hbx
|
| 3031 |
parts.append(f'<line x1="{lx:.2f}" y1="{ly:.2f}"'
|
| 3032 |
f' x2="{cbx:.2f}" y2="{cby:.2f}"'
|
| 3033 |
f' stroke="{clr}" stroke-width="1.6"'
|
| 3034 |
f'{da} opacity="0.85"/>')
|
| 3035 |
-
# Distance label — offset perpendicular to the line so it never
|
| 3036 |
-
# sits ON the dashed line or overlaps another label from same atom
|
| 3037 |
if p.get("distance") is not None:
|
| 3038 |
-
# Point 40% from ligand atom along the line
|
| 3039 |
t_along = 0.40
|
| 3040 |
bx_l = lx + (cbx - lx) * t_along
|
| 3041 |
by_l = ly + (cby - ly) * t_along
|
| 3042 |
-
# Perpendicular unit vector (rotate line direction 90°)
|
| 3043 |
dx_l = cbx - lx; dy_l = cby - ly
|
| 3044 |
_len = _math.sqrt(dx_l*dx_l + dy_l*dy_l) + 1e-9
|
| 3045 |
-
px_l = -dy_l / _len; py_l = dx_l / _len
|
| 3046 |
-
# Offset 14px perpendicular (always to the "left" of line direction)
|
| 3047 |
mx2 = bx_l + px_l * 14
|
| 3048 |
my2 = by_l + py_l * 14
|
| 3049 |
ds=f"{p['distance']}\u00c5"
|
|
@@ -3056,7 +2735,6 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 3056 |
f' font-family="Arial,sans-serif" font-size="14"'
|
| 3057 |
f' font-weight="700" fill="{clr}">{ds}</text>')
|
| 3058 |
else:
|
| 3059 |
-
# ionic / metal / halogen
|
| 3060 |
da={"ionic":"6 2 2 2","metal":"3 2","halogen":"5 2"}.get(itype,"5 3")
|
| 3061 |
parts.append(f'<line x1="{lx:.2f}" y1="{ly:.2f}"'
|
| 3062 |
f' x2="{cbx:.2f}" y2="{cby:.2f}"'
|
|
@@ -3080,26 +2758,21 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 3080 |
f' font-family="Arial,sans-serif" font-size="14"'
|
| 3081 |
f' font-weight="700" fill="{clr}">{ds}</text>')
|
| 3082 |
|
| 3083 |
-
# ── PASS 3: Ligand structure ──────────────────────────────────────────────
|
| 3084 |
parts.append(_render_ligand_svg(mol2d, svg_coords))
|
| 3085 |
|
| 3086 |
-
# ── PASS 4: Residue labels ────────────────────────────────────────────────
|
| 3087 |
for p in placements:
|
| 3088 |
itype=p["itype"]
|
| 3089 |
bx,by=p["bx"],p["by"]
|
| 3090 |
cbx=max(50,min(bx,W-50)); cby=max(70,min(by,H-65))
|
| 3091 |
rn=p["resname"]; ri=p["resid"]; ch=p.get("chain","")
|
| 3092 |
-
|
|
|
|
| 3093 |
lbl_clr=_LBL_CLR.get(itype,"#333")
|
| 3094 |
-
# st2/st3/st16: 23px bold
|
| 3095 |
parts.append(f'<text x="{cbx:.1f}" y="{cby:.1f}" text-anchor="middle"'
|
| 3096 |
f' dominant-baseline="central"'
|
| 3097 |
f' font-family="Arial,sans-serif" font-size="14.29"'
|
| 3098 |
f' font-weight="700" fill="{lbl_clr}">{lbl}</text>')
|
| 3099 |
|
| 3100 |
-
# ── PASS 5: Legend ────────────────────────────────────────────────────────
|
| 3101 |
-
# Exact SVG legend: small colored circles r=9.54 + gray 16px text
|
| 3102 |
-
# Legend box: stroke #f2f2f2 (barely visible), no fill
|
| 3103 |
_LEG_ORDER=["hydrophobic","hbond","pi_pi","cation_pi",
|
| 3104 |
"hbond_to_halogen","ionic","metal","halogen"]
|
| 3105 |
_LEG_LABEL={"hydrophobic":"Hydrophobic","hbond":"Hydrogen bond",
|
|
@@ -3109,7 +2782,6 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 3109 |
active=[t for t in _LEG_ORDER if any(p["itype"]==t for p in placements)]
|
| 3110 |
if active:
|
| 3111 |
ly0 = H - 52
|
| 3112 |
-
# Compute per-entry widths: circle(19) + line(32 if not hydrophobic) + text + gaps
|
| 3113 |
def _entry_w(t):
|
| 3114 |
txt = _LEG_LABEL.get(t, t)
|
| 3115 |
return 9.54*2 + (4+28 if t != "hydrophobic" else 0) + 6 + len(txt)*9.5 + 20
|
|
@@ -3120,31 +2792,18 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 3120 |
f' height="44" fill="white" stroke="#e0e0e0"'
|
| 3121 |
f' stroke-width="0.8" rx="6"/>')
|
| 3122 |
for k,it in enumerate(active):
|
| 3123 |
-
# Layout: circle (r=9.54) + dashed line for all types except hydrophobic
|
| 3124 |
-
# Hydrophobic: circle only (no line)
|
| 3125 |
-
# All others: circle + dashed line in that type's color
|
| 3126 |
bg = _RES_CIRCLE.get(it, dict(fill="#ccc", opacity=0.2))
|
| 3127 |
-
clr = _LINE_CLR.get(it, bg["fill"])
|
| 3128 |
lbl = _LEG_LABEL.get(it, it)
|
| 3129 |
-
|
| 3130 |
-
# Dynamic width: circle(9.54) + optional line(28) + gap(4) + text
|
| 3131 |
text_w = len(lbl) * 9.5 + 6
|
| 3132 |
glyph_w = 9.54*2 + (4 + 28 if it != "hydrophobic" else 0)
|
| 3133 |
entry_w = glyph_w + 6 + text_w
|
| 3134 |
-
ix2 = lx0 + sum(
|
| 3135 |
-
(9.54*2 + (4+28 if active[kk]!="hydrophobic" else 0) + 6 + len(_LEG_LABEL.get(active[kk],active[kk]))*9.5 + 6 + 20)
|
| 3136 |
-
for kk in range(k)
|
| 3137 |
-
) + entry_w/2
|
| 3138 |
-
|
| 3139 |
-
# Circle glyph
|
| 3140 |
circ_cx = lx0 + sum(
|
| 3141 |
(9.54*2 + (4+28 if active[kk]!="hydrophobic" else 0) + 6 + len(_LEG_LABEL.get(active[kk],active[kk]))*9.5 + 6 + 20)
|
| 3142 |
for kk in range(k)
|
| 3143 |
) + 9.54
|
| 3144 |
parts.append(f'<circle cx="{circ_cx:.1f}" cy="{ly0+10}" r="9.54"'
|
| 3145 |
f' fill="{bg["fill"]}" opacity="{bg["opacity"]}"/>')
|
| 3146 |
-
|
| 3147 |
-
# Dashed line (all except hydrophobic)
|
| 3148 |
line_x1 = circ_cx + 9.54 + 4
|
| 3149 |
line_x2 = line_x1 + 28
|
| 3150 |
if it != "hydrophobic":
|
|
@@ -3152,8 +2811,6 @@ def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
|
| 3152 |
f' x2="{line_x2:.1f}" y2="{ly0+10}"'
|
| 3153 |
f' stroke="{clr}" stroke-width="2"'
|
| 3154 |
f' stroke-dasharray="5 3" opacity="0.85"/>')
|
| 3155 |
-
|
| 3156 |
-
# Label text
|
| 3157 |
text_x = (line_x2 if it != "hydrophobic" else circ_cx + 9.54) + 6
|
| 3158 |
parts.append(f'<text x="{text_x:.1f}" y="{ly0+10}" text-anchor="start"'
|
| 3159 |
f' dominant-baseline="central"'
|
|
@@ -3177,15 +2834,7 @@ def draw_interaction_diagram(
|
|
| 3177 |
size: tuple = (800, 759),
|
| 3178 |
max_residues: int = 14,
|
| 3179 |
) -> bytes:
|
| 3180 |
-
"""
|
| 3181 |
-
2D interaction diagram — exact style matching pose1_interaction.svg.
|
| 3182 |
-
|
| 3183 |
-
Hydrophobic: translucent blue circle + blue label ONLY (no line).
|
| 3184 |
-
H-bond: green dashed line + translucent green circle + label + distance.
|
| 3185 |
-
π-π/Cat-π: magenta dashed line FROM ring centroid → residue circle + label.
|
| 3186 |
-
Ionic/Metal/Halogen: dashed line + circle + label + distance.
|
| 3187 |
-
Lines never cross (angular-sort placement).
|
| 3188 |
-
"""
|
| 3189 |
try:
|
| 3190 |
mol2d, sc, pl, W, H = _build_diagram_data(
|
| 3191 |
receptor_pdb, pose_sdf, smiles, cutoff, max_residues, size
|
|
@@ -3201,7 +2850,6 @@ def draw_interaction_diagram(
|
|
| 3201 |
return svg.encode()
|
| 3202 |
|
| 3203 |
|
| 3204 |
-
|
| 3205 |
def draw_interaction_diagram_data(
|
| 3206 |
receptor_pdb: str,
|
| 3207 |
pose_sdf: str,
|
|
@@ -3211,19 +2859,7 @@ def draw_interaction_diagram_data(
|
|
| 3211 |
size: tuple = (800, 759),
|
| 3212 |
max_residues: int = 14,
|
| 3213 |
) -> dict:
|
| 3214 |
-
"""
|
| 3215 |
-
Same pipeline as draw_interaction_diagram but returns a dict instead of SVG bytes.
|
| 3216 |
-
Used by the interactive drag-mode renderer in app.py.
|
| 3217 |
-
|
| 3218 |
-
Returns:
|
| 3219 |
-
{
|
| 3220 |
-
"W": int, "H": int, "title": str,
|
| 3221 |
-
"ligand_svg": str, # SVG fragment for the ligand (no <svg> wrapper)
|
| 3222 |
-
"placements": [...], # list of residue placement dicts
|
| 3223 |
-
"svg_coords": {...}, # atom index -> [x, y] (for line start points)
|
| 3224 |
-
}
|
| 3225 |
-
Returns None on error.
|
| 3226 |
-
"""
|
| 3227 |
from rdkit import Chem, RDLogger
|
| 3228 |
from rdkit.Chem import rdDepictor
|
| 3229 |
RDLogger.DisableLog("rdApp.*")
|
|
@@ -3266,8 +2902,6 @@ def draw_interaction_diagram_data(
|
|
| 3266 |
try: raw = _detect_all_interactions(mol3d, receptor_pdb, cutoff=cutoff)
|
| 3267 |
except: raw = []
|
| 3268 |
|
| 3269 |
-
|
| 3270 |
-
# Enrich with 3D residue positions BEFORE remapping indices to 2D
|
| 3271 |
try: _enrich_with_res_xyz(raw, mol3d, receptor_pdb)
|
| 3272 |
except: pass
|
| 3273 |
|
|
@@ -3283,16 +2917,12 @@ def draw_interaction_diagram_data(
|
|
| 3283 |
|
| 3284 |
cx, cy = W // 2, H // 2
|
| 3285 |
sc = _compute_svg_coords(mol2d, cx, cy, target_size=280)
|
| 3286 |
-
# PCA-based: initialises from projected 3D positions, mild push-apart only
|
| 3287 |
pl = _place_residues_pca(ded, sc, mol3d, cx, cy, R=210)
|
| 3288 |
|
| 3289 |
-
# Ligand SVG fragment (no wrapper svg tag)
|
| 3290 |
lig_svg = _render_ligand_svg(mol2d, sc)
|
| 3291 |
-
|
| 3292 |
-
# Serialise svg_coords as list-of-pairs (JSON-safe)
|
| 3293 |
sc_serial = {str(k): [round(v[0], 2), round(v[1], 2)] for k, v in sc.items()}
|
| 3294 |
|
| 3295 |
-
|
| 3296 |
pl_serial = []
|
| 3297 |
for p in pl:
|
| 3298 |
lx, ly = sc.get(p.get("lig_atom_idx", 0), (cx, cy))
|
|
@@ -3302,13 +2932,14 @@ def draw_interaction_diagram_data(
|
|
| 3302 |
lx, ly = rx, ry
|
| 3303 |
pl_serial.append({
|
| 3304 |
"id": f"r{len(pl_serial)}",
|
| 3305 |
-
"label":
|
|
|
|
| 3306 |
"itype": p["itype"],
|
| 3307 |
"distance": p.get("distance"),
|
| 3308 |
-
"lx": round(lx, 2),
|
| 3309 |
-
"ly": round(ly, 2),
|
| 3310 |
-
"bx": round(p["bx"], 2),
|
| 3311 |
-
"by": round(p["by"], 2),
|
| 3312 |
})
|
| 3313 |
|
| 3314 |
RDLogger.EnableLog("rdApp.error")
|
|
@@ -3322,10 +2953,7 @@ def draw_interaction_diagram_data(
|
|
| 3322 |
|
| 3323 |
def _build_diagram_data(receptor_pdb, pose_sdf, smiles, cutoff, max_residues,
|
| 3324 |
size=(800, 759)):
|
| 3325 |
-
"""
|
| 3326 |
-
Shared setup for both static SVG and interactive HTML renderers.
|
| 3327 |
-
Returns (mol2d, svg_coords, placements, W, H) or raises on error.
|
| 3328 |
-
"""
|
| 3329 |
from rdkit import Chem, RDLogger
|
| 3330 |
from rdkit.Chem import rdDepictor
|
| 3331 |
RDLogger.DisableLog("rdApp.*")
|
|
@@ -3362,8 +2990,6 @@ def _build_diagram_data(receptor_pdb, pose_sdf, smiles, cutoff, max_residues,
|
|
| 3362 |
try: raw = _detect_all_interactions(mol3d, receptor_pdb, cutoff=cutoff)
|
| 3363 |
except: raw = []
|
| 3364 |
|
| 3365 |
-
|
| 3366 |
-
# Enrich with 3D residue positions BEFORE remapping indices to 2D
|
| 3367 |
try: _enrich_with_res_xyz(raw, mol3d, receptor_pdb)
|
| 3368 |
except: pass
|
| 3369 |
|
|
@@ -3377,7 +3003,6 @@ def _build_diagram_data(receptor_pdb, pose_sdf, smiles, cutoff, max_residues,
|
|
| 3377 |
ded = ded[:max_residues]
|
| 3378 |
cx, cy = W // 2, H // 2
|
| 3379 |
sc = _compute_svg_coords(mol2d, cx, cy, target_size=280)
|
| 3380 |
-
# PCA-based: initialises from projected 3D positions, mild push-apart only
|
| 3381 |
pl = _place_residues_pca(ded, sc, mol3d, cx, cy, R=210)
|
| 3382 |
RDLogger.EnableLog("rdApp.error")
|
| 3383 |
return mol2d, sc, pl, W, H
|
|
@@ -3392,13 +3017,7 @@ def draw_interaction_diagram_interactive(
|
|
| 3392 |
size: tuple = (800, 759),
|
| 3393 |
max_residues: int = 14,
|
| 3394 |
) -> str:
|
| 3395 |
-
"""
|
| 3396 |
-
Interactive version of draw_interaction_diagram.
|
| 3397 |
-
Returns an HTML string (embed with components.html).
|
| 3398 |
-
Residue circles are draggable — lines update in real-time.
|
| 3399 |
-
Distance labels stay perpendicular to the line as you drag.
|
| 3400 |
-
Includes Reset + Export SVG buttons.
|
| 3401 |
-
"""
|
| 3402 |
import json
|
| 3403 |
|
| 3404 |
try:
|
|
@@ -3408,22 +3027,20 @@ def draw_interaction_diagram_interactive(
|
|
| 3408 |
except Exception as e:
|
| 3409 |
return f'<p style="color:red">Error: {e}</p>'
|
| 3410 |
|
| 3411 |
-
# Build ligand SVG fragment (static — never moves)
|
| 3412 |
lig_svg = _render_ligand_svg(mol2d, sc)
|
| 3413 |
|
| 3414 |
-
# Build placements JSON for JavaScript
|
| 3415 |
residues_js = []
|
| 3416 |
for p in pl:
|
| 3417 |
itype = p["itype"]
|
| 3418 |
ai = p.get("lig_atom_idx", 0)
|
| 3419 |
lx, ly = sc.get(ai, (W // 2, H // 2))
|
| 3420 |
-
# For pi-pi: start from ring centroid
|
| 3421 |
if itype in ("pi_pi", "cation_pi") and p.get("ring_atom_indices"):
|
| 3422 |
rx, ry = _ring_centroid_2d(p["ring_atom_indices"], sc)
|
| 3423 |
if rx is not None: lx, ly = rx, ry
|
| 3424 |
residues_js.append({
|
| 3425 |
"id": p["resname"] + str(p["resid"]) + p.get("chain",""),
|
| 3426 |
-
"label":
|
|
|
|
| 3427 |
"itype": itype,
|
| 3428 |
"dist": str(p["distance"]) + "Å" if p.get("distance") else "",
|
| 3429 |
"lx": round(lx, 2),
|
|
@@ -3432,7 +3049,6 @@ def draw_interaction_diagram_interactive(
|
|
| 3432 |
"by": round(p["by"], 2),
|
| 3433 |
})
|
| 3434 |
|
| 3435 |
-
# Build legend entries
|
| 3436 |
legend_types = list(dict.fromkeys(p["itype"] for p in pl))
|
| 3437 |
_LEG_LABEL = {
|
| 3438 |
"hbond":"H-bond", "hbond_to_halogen":"H···Halogen",
|
|
@@ -3441,7 +3057,6 @@ def draw_interaction_diagram_interactive(
|
|
| 3441 |
"metal":"Metal","halogen":"Halogen bond",
|
| 3442 |
}
|
| 3443 |
|
| 3444 |
-
# Title pill dimensions
|
| 3445 |
esc_title = (title.replace("&","&").replace("<","<").replace(">",">"))
|
| 3446 |
tw = min(len(esc_title) * 14 + 48, W - 40)
|
| 3447 |
pill_x = (W - tw) / 2
|
|
@@ -3507,7 +3122,7 @@ const gRes = document.getElementById("g-residues");
|
|
| 3507 |
const gLeg = document.getElementById("g-legend");
|
| 3508 |
|
| 3509 |
let pos = {{}};
|
| 3510 |
-
let els = {{}};
|
| 3511 |
|
| 3512 |
function ns(tag){{ return document.createElementNS("http://www.w3.org/2000/svg",tag); }}
|
| 3513 |
function attr(el,obj){{ for(const[k,v] of Object.entries(obj)) el.setAttribute(k,v); return el; }}
|
|
@@ -3529,7 +3144,7 @@ function drawAll(){{
|
|
| 3529 |
drawLegend();
|
| 3530 |
}}
|
| 3531 |
|
| 3532 |
-
function distLabel(r
|
| 3533 |
const cfg=TYPE_CFG[r.itype]||TYPE_CFG.hbond;
|
| 3534 |
if(!r.dist||!cfg.line) return null;
|
| 3535 |
const p=pos[r.id];
|
|
@@ -3550,7 +3165,6 @@ function drawResidue(r){{
|
|
| 3550 |
|
| 3551 |
const grp=ns("g"); grp.setAttribute("class","r-circle"); grp.setAttribute("data-id",r.id);
|
| 3552 |
|
| 3553 |
-
// Line
|
| 3554 |
let lineEl=null, drectEl=null, dtxtEl=null;
|
| 3555 |
if(cfg.line){{
|
| 3556 |
lineEl=attr(ns("line"),{{x1:r.lx,y1:r.ly,x2:p.x,y2:p.y,
|
|
@@ -3571,12 +3185,10 @@ function drawResidue(r){{
|
|
| 3571 |
}}
|
| 3572 |
}}
|
| 3573 |
|
| 3574 |
-
// Circle
|
| 3575 |
const circ=attr(ns("circle"),{{cx:p.x,cy:p.y,r:24.55,fill:cfg.fill,opacity:0.2,
|
| 3576 |
stroke:cfg.stroke,"stroke-width":1.2}});
|
| 3577 |
grp.appendChild(circ);
|
| 3578 |
|
| 3579 |
-
// Label
|
| 3580 |
const txt=attr(ns("text"),{{x:p.x,y:p.y,"text-anchor":"middle",
|
| 3581 |
"dominant-baseline":"central","font-family":"Arial,sans-serif",
|
| 3582 |
"font-size":11,"font-weight":700,fill:lclr}});
|
|
@@ -3591,7 +3203,6 @@ function drawResidue(r){{
|
|
| 3591 |
function updateResidue(r){{
|
| 3592 |
const p=pos[r.id];
|
| 3593 |
const e=els[r.id]; if(!e) return;
|
| 3594 |
-
const cfg=TYPE_CFG[r.itype]||TYPE_CFG.hbond;
|
| 3595 |
e.circ.setAttribute("cx",p.x); e.circ.setAttribute("cy",p.y);
|
| 3596 |
e.txt.setAttribute("x",p.x); e.txt.setAttribute("y",p.y);
|
| 3597 |
if(e.lineEl){{ e.lineEl.setAttribute("x2",p.x); e.lineEl.setAttribute("y2",p.y); }}
|
|
@@ -3636,7 +3247,6 @@ function makeDraggable(grp,r){{
|
|
| 3636 |
|
| 3637 |
function drawLegend(){{
|
| 3638 |
const ly0=H-48;
|
| 3639 |
-
let x=0;
|
| 3640 |
const entries=LEG_TYPES.map(t=>{{
|
| 3641 |
const cfg=TYPE_CFG[t]||TYPE_CFG.hbond;
|
| 3642 |
const lbl=LEG_LABEL[t]||t;
|
|
@@ -3646,8 +3256,6 @@ function drawLegend(){{
|
|
| 3646 |
}});
|
| 3647 |
const total=entries.reduce((s,e)=>s+e.w,0);
|
| 3648 |
let cx2=(W-total)/2;
|
| 3649 |
-
// box
|
| 3650 |
-
attr(gLeg,{{}});
|
| 3651 |
const box=attr(ns("rect"),{{x:cx2-8,y:ly0-6,width:total+16,height:42,
|
| 3652 |
fill:"white",stroke:"#e0e0e0","stroke-width":0.8,rx:6}});
|
| 3653 |
gLeg.appendChild(box);
|
|
@@ -3684,10 +3292,8 @@ window.exportSVG=function(){{
|
|
| 3684 |
|
| 3685 |
window.exportPNG=function(){{
|
| 3686 |
const scale=parseInt(document.getElementById("dpi-sel").value)||2;
|
| 3687 |
-
// Serialize the current SVG (including all dragged positions)
|
| 3688 |
const clone=svg.cloneNode(true);
|
| 3689 |
clone.setAttribute("xmlns","http://www.w3.org/2000/svg");
|
| 3690 |
-
// Force explicit pixel width/height so canvas scales correctly
|
| 3691 |
clone.setAttribute("width", W);
|
| 3692 |
clone.setAttribute("height", H);
|
| 3693 |
clone.removeAttribute("style");
|
|
@@ -3699,7 +3305,6 @@ window.exportPNG=function(){{
|
|
| 3699 |
const canvas=document.createElement("canvas");
|
| 3700 |
canvas.width=W*scale; canvas.height=H*scale;
|
| 3701 |
const ctx=canvas.getContext("2d");
|
| 3702 |
-
// White background (SVG background may be transparent in some renderers)
|
| 3703 |
ctx.fillStyle="#ffffff";
|
| 3704 |
ctx.fillRect(0,0,canvas.width,canvas.height);
|
| 3705 |
ctx.scale(scale,scale);
|
|
@@ -3724,8 +3329,6 @@ initPos(); drawAll();
|
|
| 3724 |
return html
|
| 3725 |
|
| 3726 |
|
| 3727 |
-
|
| 3728 |
-
|
| 3729 |
def draw_interactions_rdkit_classic(
|
| 3730 |
lig_mol,
|
| 3731 |
receptor_pdb: str,
|
|
@@ -3735,22 +3338,12 @@ def draw_interactions_rdkit_classic(
|
|
| 3735 |
size: tuple = (650, 620),
|
| 3736 |
max_residues: int = 10,
|
| 3737 |
) -> bytes:
|
| 3738 |
-
"""
|
| 3739 |
-
Original RDKit MolDraw2DSVG highlight-circle style.
|
| 3740 |
-
Residues shown as colored highlight circles on ligand atoms.
|
| 3741 |
-
Uses get_interacting_residues + _classify_interaction (hbond/hydrophobic/other).
|
| 3742 |
-
Returns SVG bytes.
|
| 3743 |
-
"""
|
| 3744 |
from rdkit import Chem, RDLogger
|
| 3745 |
from rdkit.Chem import Draw, rdDepictor, AllChem
|
| 3746 |
|
| 3747 |
RDLogger.DisableLog("rdApp.*")
|
| 3748 |
|
| 3749 |
-
_POLAR_RES_C = {
|
| 3750 |
-
"SER","THR","TYR","ASN","GLN","HIS","LYS","ARG",
|
| 3751 |
-
"ASP","GLU","CYS","TRP","HOH","WAT",
|
| 3752 |
-
}
|
| 3753 |
-
_HYDRO_RES_C = {"ALA","VAL","ILE","LEU","MET","PHE","TRP","PRO","GLY"}
|
| 3754 |
_C_HB = (0.35, 0.61, 0.84, 0.45)
|
| 3755 |
_C_HP = (0.17, 0.55, 0.34, 0.45)
|
| 3756 |
_C_OT = (0.80, 0.37, 0.54, 0.45)
|
|
@@ -3770,13 +3363,6 @@ def draw_interactions_rdkit_classic(
|
|
| 3770 |
except Exception:
|
| 3771 |
return None
|
| 3772 |
|
| 3773 |
-
def _classify(resname, prot_el, dist):
|
| 3774 |
-
if prot_el in {"N","O","S","F"} and dist <= 3.5:
|
| 3775 |
-
return "hbond"
|
| 3776 |
-
if resname in _HYDRO_RES_C:
|
| 3777 |
-
return "hydrophobic"
|
| 3778 |
-
return "other"
|
| 3779 |
-
|
| 3780 |
W, H = size
|
| 3781 |
mol2d = _parse_robust(smiles)
|
| 3782 |
if mol2d is None:
|
|
@@ -3799,18 +3385,14 @@ def draw_interactions_rdkit_classic(
|
|
| 3799 |
idx3d_to_2d[i3d] = i2d
|
| 3800 |
except: pass
|
| 3801 |
|
| 3802 |
-
# Get interactions via _detect_all_interactions
|
| 3803 |
try:
|
| 3804 |
-
conf = lig_mol.GetConformer()
|
| 3805 |
raw = _detect_all_interactions(lig_mol, receptor_pdb, cutoff=cutoff)
|
| 3806 |
except:
|
| 3807 |
raw = []
|
| 3808 |
|
| 3809 |
-
# Remap to 2D indices
|
| 3810 |
for ix in raw:
|
| 3811 |
ix["lig_atom_idx"] = idx3d_to_2d.get(ix.get("lig_atom_idx", 0), 0)
|
| 3812 |
|
| 3813 |
-
# Deduplicate & cap
|
| 3814 |
pm = {t: i for i, t in enumerate(_ITYPE_PRIORITY)}
|
| 3815 |
deduped = _deduplicate_interactions(raw)
|
| 3816 |
deduped.sort(key=lambda x: (pm.get(x["itype"], 99), x["distance"]))
|
|
@@ -3823,7 +3405,6 @@ def draw_interactions_rdkit_classic(
|
|
| 3823 |
RDLogger.EnableLog("rdApp.error")
|
| 3824 |
return d2d.GetDrawingText().encode()
|
| 3825 |
|
| 3826 |
-
# Build RWMol with residue pseudo-atoms + highlight mapping
|
| 3827 |
lig_ext = Chem.RWMol(mol2d)
|
| 3828 |
pts, clrs = [], {}
|
| 3829 |
|
|
@@ -3831,10 +3412,7 @@ def draw_interactions_rdkit_classic(
|
|
| 3831 |
itype = ix["itype"]
|
| 3832 |
ai = ix.get("lig_atom_idx", 0)
|
| 3833 |
if ai >= n2d: ai = 0
|
| 3834 |
-
prot_el = ix.get("prot_el", "O")
|
| 3835 |
-
dist = ix.get("distance", 3.5)
|
| 3836 |
|
| 3837 |
-
# Color by interaction type
|
| 3838 |
if itype in ("hbond", "hbond_to_halogen"):
|
| 3839 |
color = _C_HB
|
| 3840 |
elif itype == "hydrophobic":
|
|
@@ -3843,7 +3421,8 @@ def draw_interactions_rdkit_classic(
|
|
| 3843 |
color = _C_OT
|
| 3844 |
|
| 3845 |
rn = ix["resname"]; ri = ix["resid"]; ch = ix.get("chain","")
|
| 3846 |
-
|
|
|
|
| 3847 |
|
| 3848 |
res_atom = Chem.Atom(0)
|
| 3849 |
res_atom.SetProp("atomLabel", lbl)
|
|
|
|
| 14 |
Retries up to 3x, strips explicit Hs from receptor, polls up to 120 s.
|
| 15 |
- warm_poseview_cache: now a no-op (MoleculeHandler pre-upload removed)
|
| 16 |
- call_poseview2_ref: retry + full-response logging
|
| 17 |
+
- Heme: _AROM_ATOMS / _AROM_ATOM_NAMES extended for porphyrin π-detection
|
| 18 |
+
- Heme: hydrophobic detection extended to heme residue names
|
| 19 |
- Minor: type annotations, cleaner log messages
|
| 20 |
"""
|
| 21 |
|
|
|
|
| 58 |
"EPE", "MES", "TRS", "ACT", "ACY",
|
| 59 |
}
|
| 60 |
|
| 61 |
+
HEME_RESNAMES = {"HEM", "HEC", "HEA", "HEB", "HDD", "HDM"}
|
| 62 |
+
|
| 63 |
# PoseView: max retries on "failure" before giving up
|
| 64 |
_PV_MAX_RETRIES = 3
|
| 65 |
# PoseView: seconds to wait between retries
|
|
|
|
| 280 |
# RECEPTOR PREPARATION
|
| 281 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 282 |
|
| 283 |
+
# Minimum heavy atoms for a HETATM group to be treated as a real ligand.
|
| 284 |
+
# Groups with ≤ this count are treated as ions/solvent and ignored.
|
| 285 |
+
_MIN_LIG_ATOMS = 4
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _collect_removable_ligands(atoms) -> list:
|
| 289 |
+
"""
|
| 290 |
+
Return a list of dicts, one per HETATM residue that qualifies as a
|
| 291 |
+
"drug-like" molecule to be removed from the receptor before docking.
|
| 292 |
+
|
| 293 |
+
Qualification rules (all must pass):
|
| 294 |
+
• Not in EXCLUDE_IONS, GLYCAN_NAMES, COFACTOR_NAMES,
|
| 295 |
+
HEME_RESNAMES, or METAL_RESNAMES (those are handled separately)
|
| 296 |
+
• Has > _MIN_LIG_ATOMS heavy atoms (filters out ions / small solvent)
|
| 297 |
+
|
| 298 |
+
Each dict has keys: resname, chain, resid, sel_str, n_atoms, atoms
|
| 299 |
+
Sorted descending by atom count (largest = primary co-crystal ligand).
|
| 300 |
+
"""
|
| 301 |
+
from prody import calcCenter
|
| 302 |
+
|
| 303 |
+
excl = EXCLUDE_IONS | GLYCAN_NAMES | COFACTOR_NAMES | HEME_RESNAMES | METAL_RESNAMES
|
| 304 |
+
# Use "hetatm" not "hetero": ProDy's "hetero" = "hetatm AND NOT protein".
|
| 305 |
+
# Non-standard resnames (MOL, LIG, UNL, etc.) are sometimes incorrectly
|
| 306 |
+
# flagged as protein=True by ProDy, so "hetero" silently drops them.
|
| 307 |
+
# "hetatm" selects purely on the HETATM record type — always correct.
|
| 308 |
+
het = atoms.select("hetatm and not water")
|
| 309 |
+
|
| 310 |
+
# Backbone atom names that identify a residue as a modified amino acid.
|
| 311 |
+
# If a HETATM residue contains ALL four backbone atoms it is treated as
|
| 312 |
+
# part of the protein (e.g. CYP = proximal cysteine in CYP450 enzymes,
|
| 313 |
+
# MSE = selenomethionine, etc.) and must NOT be removed as a ligand.
|
| 314 |
+
_BACKBONE = {"N", "CA", "C", "O"}
|
| 315 |
+
if het is None:
|
| 316 |
+
return []
|
| 317 |
+
|
| 318 |
+
results = []
|
| 319 |
+
for r in het.getHierView().iterResidues():
|
| 320 |
+
rn = (r.getResname() or "").strip().upper()
|
| 321 |
+
if rn in excl:
|
| 322 |
+
continue
|
| 323 |
+
if r.numAtoms() <= _MIN_LIG_ATOMS:
|
| 324 |
+
continue # too small — ion / solvent fragment
|
| 325 |
+
# Skip modified amino acids: residues that contain all 4 backbone
|
| 326 |
+
# heavy atoms (N, CA, C, O) are protein residues stored as HETATM
|
| 327 |
+
# (e.g. CYP = proximal Cys in P450, MSE = selenomethionine, etc.)
|
| 328 |
+
_atom_names = set(r.getNames())
|
| 329 |
+
if _BACKBONE.issubset(_atom_names):
|
| 330 |
+
continue
|
| 331 |
+
ch = r.getChid()
|
| 332 |
+
ri = r.getResnum()
|
| 333 |
+
sel = (f"resname {rn} and resid {ri} and chain {ch}"
|
| 334 |
+
if ch and ch.strip()
|
| 335 |
+
else f"resname {rn} and resid {ri}")
|
| 336 |
+
lig_atoms = atoms.select(sel)
|
| 337 |
+
if lig_atoms is None or lig_atoms.numAtoms() == 0:
|
| 338 |
+
continue
|
| 339 |
+
cx_, cy_, cz_ = (float(v) for v in calcCenter(lig_atoms))
|
| 340 |
+
results.append({
|
| 341 |
+
"resname": rn,
|
| 342 |
+
"chain": ch,
|
| 343 |
+
"resid": ri,
|
| 344 |
+
"sel_str": sel,
|
| 345 |
+
"ligand_id": f"{rn}_{ch}_{ri}",
|
| 346 |
+
"n_atoms": lig_atoms.numAtoms(),
|
| 347 |
+
"atoms": lig_atoms,
|
| 348 |
+
"cx": cx_, "cy": cy_, "cz": cz_,
|
| 349 |
+
})
|
| 350 |
+
|
| 351 |
+
# Sort: largest first, chain A preferred on tie
|
| 352 |
+
results.sort(key=lambda d: (-d["n_atoms"], d["chain"] != "A"))
|
| 353 |
+
return results
|
| 354 |
+
|
| 355 |
+
|
| 356 |
def detect_cocrystal_ligand(raw_pdb: str) -> dict:
|
| 357 |
"""
|
| 358 |
+
Parse PDB and return the best co-crystal ligand candidate
|
| 359 |
+
(largest HETATM residue with > _MIN_LIG_ATOMS atoms that is not
|
| 360 |
+
a known cofactor, heme, metal, ion, or glycan).
|
| 361 |
+
|
| 362 |
Returns dict with keys:
|
| 363 |
found, resname, chain, resid, sel_str, ligand_id,
|
| 364 |
cx, cy, cz, n_atoms, atoms
|
| 365 |
"""
|
| 366 |
+
from prody import parsePDB
|
| 367 |
|
| 368 |
atoms = parsePDB(raw_pdb)
|
| 369 |
if atoms is None:
|
| 370 |
return {"found": False}
|
| 371 |
|
| 372 |
+
cands = _collect_removable_ligands(atoms)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
if not cands:
|
| 374 |
return {"found": False}
|
| 375 |
|
| 376 |
+
chosen = cands[0] # largest qualifying residue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
return {
|
| 378 |
"found": True,
|
| 379 |
+
"resname": chosen["resname"],
|
| 380 |
+
"chain": chosen["chain"],
|
| 381 |
+
"resid": chosen["resid"],
|
| 382 |
+
"sel_str": chosen["sel_str"],
|
| 383 |
+
"ligand_id": chosen["ligand_id"],
|
| 384 |
+
"cx": chosen["cx"], "cy": chosen["cy"], "cz": chosen["cz"],
|
| 385 |
+
"n_atoms": chosen["n_atoms"],
|
| 386 |
+
"atoms": chosen["atoms"],
|
| 387 |
}
|
| 388 |
|
| 389 |
|
|
|
|
| 572 |
ri = 0
|
| 573 |
cx = cy = cz = 0.0
|
| 574 |
|
| 575 |
+
# ── Detect ALL removable ligands (>_MIN_LIG_ATOMS atoms, non-cofactor) ─
|
| 576 |
+
# This runs for every center mode so the receptor is always clean.
|
| 577 |
+
_all_ligs = _collect_removable_ligands(atoms)
|
| 578 |
+
_primary = _all_ligs[0] if _all_ligs else None
|
| 579 |
+
|
| 580 |
+
# Save primary ligand PDB for RMSD, 3D viewer, PoseView2
|
| 581 |
+
if _primary is not None:
|
| 582 |
+
rn = _primary["resname"]
|
| 583 |
+
ch = _primary["chain"]
|
| 584 |
+
ri = _primary["resid"]
|
| 585 |
+
ligand_sel_str = _primary["sel_str"]
|
| 586 |
+
cocrystal_ligand_id = _primary["ligand_id"]
|
| 587 |
+
ligand_pdb_path = str(wdir / "LIG.pdb")
|
| 588 |
+
writePDB(ligand_pdb_path, _primary["atoms"])
|
| 589 |
+
_n_extra = len(_all_ligs) - 1
|
| 590 |
+
log.append(
|
| 591 |
+
f"✓ Co-crystal ligand: {rn} chain '{ch}' resnum {ri} "
|
| 592 |
+
f"({_primary['n_atoms']} atoms)"
|
| 593 |
+
+ (f" +{_n_extra} additional ligand(s) will also be removed" if _n_extra else "")
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
if center_mode == "auto":
|
| 597 |
+
if _primary is not None:
|
| 598 |
+
cx, cy, cz = _primary["cx"], _primary["cy"], _primary["cz"]
|
| 599 |
+
log.append(f"📍 Auto center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
log.append(f"🔑 PoseView2 ligand ID: {cocrystal_ligand_id}")
|
| 601 |
else:
|
| 602 |
+
log.append("⚠ No co-crystal ligand found (all HETATM ≤ 4 atoms or excluded)")
|
| 603 |
|
| 604 |
elif center_mode == "manual":
|
| 605 |
cx, cy, cz = (float(v) for v in manual_xyz)
|
| 606 |
log.append(f"🛠 Manual center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
|
| 607 |
+
if _primary is not None:
|
| 608 |
+
log.append(f"🔑 PoseView2 ligand ID: {cocrystal_ligand_id}")
|
| 609 |
|
| 610 |
elif center_mode == "selection":
|
| 611 |
if not prody_sel.strip():
|
|
|
|
| 621 |
f"→ {ref_atoms.numAtoms()} atoms"
|
| 622 |
)
|
| 623 |
log.append(f"📍 Center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
|
| 624 |
+
if _primary is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
log.append(f"🔑 PoseView2 ligand ID: {cocrystal_ligand_id}")
|
| 626 |
else:
|
| 627 |
+
log.append("⚠ No co-crystal ligand found — RMSD and co-crystal diagrams skipped")
|
| 628 |
+
|
| 629 |
+
# ── Build receptor selection: exclude ALL removable ligands + water ───
|
| 630 |
+
# Each ligand's sel_str is negated so multi-ligand structures are
|
| 631 |
+
# fully cleaned regardless of which center mode was chosen.
|
| 632 |
+
if _all_ligs:
|
| 633 |
+
_excl_expr = " or ".join(f"({d['sel_str']})" for d in _all_ligs)
|
| 634 |
+
sel_str = f"not ({_excl_expr}) and not water"
|
| 635 |
+
if len(_all_ligs) > 1:
|
| 636 |
log.append(
|
| 637 |
+
f"🧹 Removing {len(_all_ligs)} ligand(s) from receptor: "
|
| 638 |
+
+ ", ".join(f"{d['resname']}({d['n_atoms']}at)" for d in _all_ligs)
|
| 639 |
)
|
| 640 |
+
else:
|
| 641 |
+
sel_str = "not water"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
rec_sel = atoms.select(sel_str)
|
| 643 |
if rec_sel is None or rec_sel.numAtoms() == 0:
|
| 644 |
raise ValueError("Receptor selection returned no atoms")
|
|
|
|
| 647 |
writePDB(rec_raw_path, rec_sel)
|
| 648 |
log.append(f"✓ Receptor: {rec_sel.numAtoms()} atoms")
|
| 649 |
|
| 650 |
+
# ── Fix blank chain IDs ───────────────────────────────────────────
|
| 651 |
+
# PDB files from MD software (GROMACS, AMBER, etc.) often have no
|
| 652 |
+
# chain ID (space). OpenBabel and Vina both require a real chain
|
| 653 |
+
# letter — a fully-blank-chain receptor causes Vina exit code 1.
|
| 654 |
+
# If ALL atom/HETATM records have blank chain, assign chain A.
|
| 655 |
+
try:
|
| 656 |
+
_rec_lines = open(rec_raw_path).readlines()
|
| 657 |
+
_coord_lines = [l for l in _rec_lines if l[:6].strip() in ("ATOM", "HETATM")]
|
| 658 |
+
_all_blank = all(
|
| 659 |
+
(l[21] == " " if len(l) > 21 else True)
|
| 660 |
+
for l in _coord_lines
|
| 661 |
+
)
|
| 662 |
+
if _all_blank and _coord_lines:
|
| 663 |
+
_fixed = []
|
| 664 |
+
for l in _rec_lines:
|
| 665 |
+
if l[:6].strip() in ("ATOM", "HETATM") and len(l) > 21:
|
| 666 |
+
l = l[:21] + "A" + l[22:]
|
| 667 |
+
_fixed.append(l)
|
| 668 |
+
with open(rec_raw_path, "w") as _f:
|
| 669 |
+
_f.writelines(_fixed)
|
| 670 |
+
log.append("✓ Assigned chain A to all blank-chain atoms")
|
| 671 |
+
except Exception as _ce:
|
| 672 |
+
log.append(f"⚠ Chain-fix skipped: {_ce}")
|
| 673 |
+
# ─────────────────────────────────────────────────────────────────
|
| 674 |
+
|
| 675 |
# PDBQT conversion (metal-safe)
|
| 676 |
conv = strip_and_convert_receptor(rec_raw_path, wdir)
|
| 677 |
log.extend(conv["log"])
|
|
|
|
| 820 |
if mols:
|
| 821 |
mol = mols[0]
|
| 822 |
elif ext in (".mol2", ".pdb"):
|
|
|
|
| 823 |
_ob_sdf = str(wdir / f"{name}_ob.sdf")
|
| 824 |
import subprocess
|
| 825 |
subprocess.run(
|
|
|
|
| 835 |
if mols:
|
| 836 |
mol = mols[0]
|
| 837 |
log.append("✓ Converted via OpenBabel")
|
|
|
|
| 838 |
if mol is None:
|
| 839 |
if ext == ".mol2":
|
| 840 |
mol = Chem.MolFromMol2File(file_path, removeHs=False, sanitize=True)
|
|
|
|
| 848 |
if mol is None:
|
| 849 |
raise ValueError(f"Could not read molecule from {Path(file_path).name}")
|
| 850 |
|
|
|
|
| 851 |
frags = Chem.GetMolFrags(mol, asMols=True, sanitizeFrags=False)
|
| 852 |
if len(frags) > 1:
|
| 853 |
frags = sorted(frags, key=lambda m: m.GetNumAtoms(), reverse=True)
|
| 854 |
mol = frags[0]
|
| 855 |
log.append(f"⚠ {len(frags)} fragments — kept largest ({mol.GetNumAtoms()} atoms)")
|
| 856 |
|
|
|
|
| 857 |
try:
|
| 858 |
Chem.SanitizeMol(mol)
|
| 859 |
except Exception:
|
|
|
|
| 861 |
|
| 862 |
log.append("✓ Loaded molecule from file (no protonation)")
|
| 863 |
|
|
|
|
| 864 |
try:
|
| 865 |
smi = Chem.MolToSmiles(Chem.RemoveHs(mol))
|
| 866 |
except Exception:
|
|
|
|
| 874 |
charge = 0
|
| 875 |
log.append(f"✓ Formal charge: {charge:+d}")
|
| 876 |
|
|
|
|
| 877 |
mol = Chem.AddHs(mol, addCoords=True)
|
| 878 |
log.append("✓ All hydrogens made explicit")
|
| 879 |
|
|
|
|
| 880 |
conf = mol.GetConformer(0) if mol.GetNumConformers() > 0 else None
|
| 881 |
if conf is None or conf.Is3D() is False:
|
| 882 |
try:
|
|
|
|
| 1056 |
def fix_sdf_bond_orders(raw_sdf: str, smiles: str, fixed_sdf: str) -> list:
|
| 1057 |
"""
|
| 1058 |
Apply bond-order + formal-charge correction to all poses in an SDF.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1059 |
Returns list of log messages.
|
| 1060 |
"""
|
| 1061 |
import shutil
|
| 1062 |
from rdkit import Chem, RDLogger
|
| 1063 |
from rdkit.Chem import AllChem
|
| 1064 |
|
|
|
|
| 1065 |
RDLogger.DisableLog("rdApp.*")
|
| 1066 |
|
| 1067 |
log = []
|
|
|
|
| 1087 |
try:
|
| 1088 |
fixed = _bo_fix_mol(mol, template)
|
| 1089 |
|
|
|
|
| 1090 |
try:
|
| 1091 |
fixed_h = Chem.AddHs(fixed, addCoords=True)
|
| 1092 |
conf = fixed_h.GetConformer()
|
|
|
|
| 1093 |
bad = any(
|
| 1094 |
abs(conf.GetAtomPosition(j).x)
|
| 1095 |
+ abs(conf.GetAtomPosition(j).y)
|
|
|
|
| 1099 |
)
|
| 1100 |
writer.write(fixed if bad else fixed_h)
|
| 1101 |
except Exception:
|
|
|
|
| 1102 |
writer.write(fixed)
|
| 1103 |
|
| 1104 |
ok += 1
|
|
|
|
| 1119 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 1120 |
|
| 1121 |
def load_mols_from_sdf(sdf_path: str, sanitize: bool = True) -> list:
|
| 1122 |
+
"""Load all valid mols from an SDF file."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1123 |
from rdkit import Chem, RDLogger
|
| 1124 |
|
|
|
|
|
|
|
| 1125 |
RDLogger.DisableLog("rdApp.*")
|
| 1126 |
|
| 1127 |
mols = []
|
|
|
|
| 1133 |
except Exception:
|
| 1134 |
pass
|
| 1135 |
|
|
|
|
| 1136 |
if sanitize:
|
| 1137 |
try:
|
| 1138 |
sup2 = Chem.SDMolSupplier(sdf_path, sanitize=False, removeHs=False)
|
|
|
|
| 1143 |
try:
|
| 1144 |
Chem.SanitizeMol(m)
|
| 1145 |
except Exception:
|
| 1146 |
+
pass
|
| 1147 |
result.append(m)
|
| 1148 |
RDLogger.EnableLog("rdApp.error")
|
| 1149 |
return result
|
|
|
|
| 1162 |
|
| 1163 |
|
| 1164 |
def convert_sdf_to_v2000(sdf_path: str) -> str:
|
| 1165 |
+
"""Convert an SDF to Kekulized V2000 format suitable for PoseView."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1166 |
from rdkit import Chem, RDLogger
|
| 1167 |
|
| 1168 |
out = sdf_path.replace(".sdf", "_v2000.sdf")
|
| 1169 |
if out == sdf_path:
|
| 1170 |
out = sdf_path + "_v2000.sdf"
|
| 1171 |
|
|
|
|
| 1172 |
RDLogger.DisableLog("rdApp.*")
|
| 1173 |
try:
|
|
|
|
| 1174 |
mol = None
|
| 1175 |
for sanitize in (True, False):
|
| 1176 |
sup = Chem.SDMolSupplier(sdf_path, sanitize=sanitize, removeHs=True)
|
|
|
|
| 1189 |
Chem.SanitizeMol(mol_noH)
|
| 1190 |
except Exception:
|
| 1191 |
pass
|
|
|
|
|
|
|
| 1192 |
try:
|
| 1193 |
Chem.Kekulize(mol_noH, clearAromaticFlags=True)
|
| 1194 |
except Exception:
|
| 1195 |
+
pass
|
| 1196 |
|
| 1197 |
w = Chem.SDWriter(out)
|
| 1198 |
+
w.SetKekulize(True)
|
| 1199 |
w.write(mol_noH)
|
| 1200 |
w.close()
|
| 1201 |
|
|
|
|
| 1206 |
pass
|
| 1207 |
RDLogger.EnableLog("rdApp.error")
|
| 1208 |
|
|
|
|
| 1209 |
rc, _ = run_cmd(f'obabel "{sdf_path}" -O "{out}" 2>/dev/null')
|
| 1210 |
if rc == 0 and os.path.exists(out) and os.path.getsize(out) > 10:
|
| 1211 |
return out
|
|
|
|
| 1367 |
|
| 1368 |
def _pp_poll(job_id: str, poll_url: str, poll_interval: int = 2,
|
| 1369 |
max_polls: int = 60) -> dict:
|
| 1370 |
+
"""Poll a ProteinsPlus job until it leaves pending/running state."""
|
|
|
|
|
|
|
|
|
|
| 1371 |
import requests
|
| 1372 |
job = requests.get(poll_url + job_id + "/", headers=_PP_HEADERS, timeout=15).json()
|
| 1373 |
status = str(job.get("status", "")).lower()
|
|
|
|
| 1386 |
|
| 1387 |
|
| 1388 |
def _prepare_pdb_for_poseview(receptor_pdb: str) -> str:
|
| 1389 |
+
"""Write a minimal, clean PDB suitable for PoseView's CDK-based parser."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1390 |
rec_dir = os.path.dirname(os.path.abspath(receptor_pdb))
|
| 1391 |
candidates = [
|
| 1392 |
os.path.join(rec_dir, "receptor_atoms.pdb"),
|
|
|
|
| 1401 |
with open(source) as f:
|
| 1402 |
for line in f:
|
| 1403 |
rec = line[:6].strip()
|
|
|
|
|
|
|
| 1404 |
if rec not in ("ATOM", "HETATM", "TER", "END"):
|
| 1405 |
continue
|
|
|
|
| 1406 |
if rec in ("ATOM", "HETATM"):
|
|
|
|
| 1407 |
atom_name = line[12:16].strip()
|
| 1408 |
element = line[76:78].strip() if len(line) > 76 else ""
|
| 1409 |
if element.upper() == "H" or (not element and atom_name.startswith("H")):
|
| 1410 |
continue
|
|
|
|
|
|
|
|
|
|
| 1411 |
serial += 1
|
| 1412 |
line = f"{line[:6]}{serial:5d}{line[11:]}"
|
|
|
|
| 1413 |
kept.append(line if line.endswith("\n") else line + "\n")
|
| 1414 |
|
| 1415 |
if not kept:
|
| 1416 |
return receptor_pdb
|
| 1417 |
|
|
|
|
| 1418 |
if not any(l.startswith("END") for l in kept):
|
| 1419 |
kept.append("END\n")
|
| 1420 |
|
|
|
|
| 1432 |
def call_poseview_v1(receptor_pdb: str, pose_sdf: str) -> tuple:
|
| 1433 |
"""
|
| 1434 |
Submit receptor PDB + docked pose SDF to PoseView v1 REST API.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1435 |
Returns (svg_bytes, error_string) — one will be None.
|
| 1436 |
"""
|
| 1437 |
import requests
|
| 1438 |
|
| 1439 |
last_error = "Unknown error"
|
|
|
|
|
|
|
|
|
|
| 1440 |
rec_to_send = _prepare_pdb_for_poseview(receptor_pdb)
|
| 1441 |
|
| 1442 |
for attempt in range(1, _PV_MAX_RETRIES + 1):
|
| 1443 |
if attempt > 1:
|
| 1444 |
time.sleep(_PV_RETRY_DELAY)
|
| 1445 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1446 |
try:
|
| 1447 |
with open(rec_to_send) as rf, open(pose_sdf) as lf:
|
| 1448 |
r = requests.post(
|
|
|
|
| 1464 |
last_error = f"PoseView submission failed (attempt {attempt}): {e}"
|
| 1465 |
continue
|
| 1466 |
|
|
|
|
| 1467 |
try:
|
| 1468 |
pv_job = _pp_poll(pv_job_id, _PP_POSEVIEW_JOBS)
|
| 1469 |
status = str(pv_job.get("status", "")).lower()
|
|
|
|
| 1506 |
|
| 1507 |
|
| 1508 |
def warm_poseview_cache(receptor_pdb: str) -> tuple:
|
| 1509 |
+
"""No-op — kept for API compatibility with app.py."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1510 |
return True, "Direct POST mode — no pre-upload needed"
|
| 1511 |
|
| 1512 |
|
|
|
|
| 1523 |
import requests
|
| 1524 |
|
| 1525 |
_SUBMIT = "https://proteins.plus/api/poseview2_rest"
|
|
|
|
| 1526 |
last_error = "Unknown error"
|
| 1527 |
|
| 1528 |
for attempt in range(1, _PV_MAX_RETRIES + 1):
|
|
|
|
| 1621 |
|
| 1622 |
|
| 1623 |
def stamp_png(png_bytes: bytes, text: str) -> bytes:
|
| 1624 |
+
"""Burn a centred label pill into the bottom of a PNG."""
|
|
|
|
|
|
|
|
|
|
| 1625 |
try:
|
| 1626 |
from PIL import Image, ImageDraw, ImageFont
|
| 1627 |
import io as _io
|
|
|
|
| 1676 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 1677 |
|
| 1678 |
def diagnose_poseview() -> dict:
|
| 1679 |
+
"""Test the PoseView API with a known-good minimal PDB + SDF from RCSB."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1680 |
import requests
|
| 1681 |
|
| 1682 |
result = {
|
|
|
|
| 1771 |
|
| 1772 |
|
| 1773 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 1774 |
+
# CUSTOM 2D INTERACTION DIAGRAM
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1775 |
# ═══════════════════════════════════════════════════════════════════════════��══
|
| 1776 |
|
| 1777 |
import math as _math
|
|
|
|
| 1781 |
"hbond", "pi_pi", "cation_pi", "hydrophobic",
|
| 1782 |
]
|
| 1783 |
|
| 1784 |
+
_CLR_HBOND = "#1a7a1a"
|
| 1785 |
+
_CLR_PIPI = "#e200e8"
|
| 1786 |
+
_CLR_HYDRO = "#2287ff"
|
|
|
|
| 1787 |
_CLR_IONIC = "#aa0077"
|
| 1788 |
_CLR_METAL = "#cc8800"
|
| 1789 |
_CLR_HAL = "#cc2277"
|
| 1790 |
_CLR_HBXHAL = "#6633aa"
|
| 1791 |
|
|
|
|
| 1792 |
_RES_CIRCLE = {
|
| 1793 |
+
"hbond": dict(fill="#80dd80", opacity=0.2),
|
| 1794 |
"hbond_to_halogen": dict(fill="#80dd80", opacity=0.2),
|
| 1795 |
+
"pi_pi": dict(fill="#e200e8", opacity=0.2),
|
| 1796 |
"cation_pi": dict(fill="#e200e8", opacity=0.2),
|
| 1797 |
+
"hydrophobic": dict(fill="#2287ff", opacity=0.2),
|
| 1798 |
"ionic": dict(fill="#ffaae0", opacity=0.2),
|
| 1799 |
"metal": dict(fill="#ffe080", opacity=0.2),
|
| 1800 |
"halogen": dict(fill="#ffb0d0", opacity=0.2),
|
| 1801 |
}
|
| 1802 |
|
| 1803 |
_LBL_CLR = {
|
| 1804 |
+
"hbond": _CLR_HBOND,
|
| 1805 |
"hbond_to_halogen": _CLR_HBOND,
|
| 1806 |
+
"pi_pi": _CLR_PIPI,
|
| 1807 |
"cation_pi": _CLR_PIPI,
|
| 1808 |
+
"hydrophobic": _CLR_HYDRO,
|
| 1809 |
"ionic": _CLR_IONIC,
|
| 1810 |
"metal": _CLR_METAL,
|
| 1811 |
"halogen": _CLR_HAL,
|
| 1812 |
}
|
| 1813 |
|
| 1814 |
_LINE_CLR = {
|
| 1815 |
+
"hbond": _CLR_HBOND,
|
| 1816 |
"hbond_to_halogen": _CLR_HBXHAL,
|
| 1817 |
+
"pi_pi": _CLR_PIPI,
|
| 1818 |
"cation_pi": _CLR_PIPI,
|
| 1819 |
"ionic": _CLR_IONIC,
|
| 1820 |
"metal": _CLR_METAL,
|
|
|
|
| 1827 |
"S":"#c8a800", "P":"#e07000", "F":"#1a7a1a",
|
| 1828 |
"CL":"#1a7a1a", "BR":"#8b2500", "I":"#5c2d8a", "H":"#555555",
|
| 1829 |
}
|
| 1830 |
+
_AROM_DOT_CLR = "#1a7a1a"
|
| 1831 |
|
| 1832 |
_METALS_SET = {"MG","ZN","CA","MN","FE","CU","CO","NI","CD","HG","NA","K"}
|
| 1833 |
+
|
| 1834 |
+
# ── Aromatic residues: amino acids + heme porphyrin ──────────────────────────
|
| 1835 |
+
_AROM_ATOMS = {"PHE","TYR","TRP","HIS","HEM","HEC","HEA","HEB","HDD","HDM"}
|
| 1836 |
+
|
| 1837 |
+
# ── Aromatic atom names: amino acid rings + heme porphyrin macrocycle ─────────
|
| 1838 |
_AROM_ATOM_NAMES = {
|
| 1839 |
+
# Amino acid aromatic ring atoms
|
| 1840 |
"CG","CD1","CD2","CE1","CE2","CZ",
|
| 1841 |
"ND1","NE2","CE3","CZ2","CZ3","CH2",
|
| 1842 |
+
# Heme porphyrin macrocycle carbons
|
| 1843 |
+
"C1","C2","C3","C4","C5","C6","C7","C8",
|
| 1844 |
+
"C10","C11","C12","C13","C14","C15","C16","C17",
|
| 1845 |
+
"C19","C20",
|
| 1846 |
+
"CA","CB", # pyrrole alpha/beta carbons
|
| 1847 |
}
|
| 1848 |
|
| 1849 |
+
# ── Hydrophobic residues: amino acids + heme ─────────────────────────────────
|
| 1850 |
+
_HYDR_BASE = {"ALA","VAL","ILE","LEU","MET","PHE","TRP","PRO","GLY","TYR","HIS"}
|
| 1851 |
+
_HYDR_EXTENDED = _HYDR_BASE | HEME_RESNAMES
|
| 1852 |
+
|
| 1853 |
|
| 1854 |
# ──────────────────────────────────────────────────────────────────────────────
|
| 1855 |
# INTERACTION DETECTION
|
|
|
|
| 1868 |
v1 = coords[1]-coords[0]; v2 = coords[2]-coords[0]
|
| 1869 |
n = np.cross(v1,v2); nl = np.linalg.norm(n)
|
| 1870 |
if nl > 0: n /= nl
|
| 1871 |
+
results.append((centroid, n, list(ring)))
|
| 1872 |
return results
|
| 1873 |
|
| 1874 |
|
|
|
|
| 1876 |
cutoff: float = 4.5) -> list:
|
| 1877 |
"""
|
| 1878 |
Detect protein-ligand interactions with proper geometry criteria.
|
| 1879 |
+
Includes heme Fe coordination (metal), H-bonds to heme N/O,
|
| 1880 |
+
π-stacking with porphyrin, and hydrophobic contacts with heme carbons.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1881 |
"""
|
| 1882 |
import numpy as np
|
| 1883 |
from prody import parsePDB
|
|
|
|
| 1886 |
if rec is None:
|
| 1887 |
return []
|
| 1888 |
|
| 1889 |
+
rc = np.array(rec.getCoords(), dtype=float)
|
| 1890 |
rrn = rec.getResnames()
|
| 1891 |
rch = rec.getChids()
|
| 1892 |
rri = rec.getResnums()
|
|
|
|
| 1902 |
lel = [a.GetSymbol().upper() for a in latom]
|
| 1903 |
lchg = [a.GetFormalCharge() for a in latom]
|
| 1904 |
|
|
|
|
| 1905 |
_VDW = {"H":1.20,"C":1.70,"N":1.55,"O":1.52,"S":1.80,"P":1.80,
|
| 1906 |
"F":1.47,"CL":1.75,"BR":1.85,"I":1.98,"SE":1.90}
|
| 1907 |
|
|
|
|
| 1908 |
nr = len(rc)
|
| 1909 |
r_el = [rel[j].strip().upper() if rel[j] and rel[j].strip()
|
| 1910 |
else ran[j][:1].upper() for j in range(nr)]
|
| 1911 |
+
r_el_arr = np.array(r_el)
|
| 1912 |
r_rn = np.array([rrn[j].strip() for j in range(nr)])
|
| 1913 |
r_an = np.array([ran[j].strip() for j in range(nr)])
|
| 1914 |
r_ch = np.array([rch[j].strip() for j in range(nr)])
|
| 1915 |
r_ri = np.array([int(rri[j]) for j in range(nr)])
|
| 1916 |
|
|
|
|
| 1917 |
HYDL = {"C","S","CL","BR","I","F"}
|
|
|
|
| 1918 |
LIG_ACCEPTOR_EL = {"N","O","F","S"}
|
| 1919 |
|
| 1920 |
+
lig_is_acceptor = np.array([lel[i] in LIG_ACCEPTOR_EL for i in range(nl)])
|
| 1921 |
lig_is_hydrophobic = np.array([lel[i] in HYDL for i in range(nl)])
|
| 1922 |
|
| 1923 |
def _is_lig_donor(i):
|
|
|
|
| 1929 |
|
| 1930 |
lig_is_donor = np.array([_is_lig_donor(i) for i in range(nl)])
|
| 1931 |
|
|
|
|
| 1932 |
def _angles_at_b(a_pts, b_pt, c_pt):
|
| 1933 |
+
va = a_pts - b_pt
|
| 1934 |
+
vc = c_pt - b_pt
|
| 1935 |
+
na = np.linalg.norm(va, axis=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1936 |
nc = float(np.linalg.norm(vc))
|
| 1937 |
if nc < 1e-8: return np.zeros(len(a_pts))
|
| 1938 |
+
cos_t = (va @ vc) / (na * nc + 1e-12)
|
| 1939 |
cos_t = np.clip(cos_t, -1.0, 1.0)
|
| 1940 |
return np.degrees(np.arccos(cos_t))
|
| 1941 |
|
| 1942 |
def _angle3(a, b, c):
|
|
|
|
| 1943 |
va = a - b; vc = c - b
|
| 1944 |
na = np.linalg.norm(va); nc = np.linalg.norm(vc)
|
| 1945 |
if na < 1e-8 or nc < 1e-8: return 0.0
|
| 1946 |
return float(np.degrees(np.arccos(
|
| 1947 |
np.clip(np.dot(va, vc) / (na * nc), -1.0, 1.0))))
|
| 1948 |
|
|
|
|
| 1949 |
h_mask = r_el_arr == "H"
|
| 1950 |
+
h_idx = np.where(h_mask)[0]
|
| 1951 |
+
heavy_idx = np.where(~h_mask)[0]
|
| 1952 |
|
| 1953 |
+
h_to_heavy = {}
|
| 1954 |
if len(h_idx) and len(heavy_idx):
|
| 1955 |
+
h_coords = rc[h_idx]
|
| 1956 |
+
hv_coords = rc[heavy_idx]
|
| 1957 |
+
diff = h_coords[:, None, :] - hv_coords[None, :, :]
|
| 1958 |
+
dists_hh = np.linalg.norm(diff, axis=2)
|
| 1959 |
+
closest = np.argmin(dists_hh, axis=1)
|
| 1960 |
+
min_d = dists_hh[np.arange(len(h_idx)), closest]
|
|
|
|
|
|
|
| 1961 |
for k, (hi, ci, md) in enumerate(zip(h_idx, closest, min_d)):
|
| 1962 |
if md < 1.15:
|
| 1963 |
h_to_heavy[int(hi)] = int(heavy_idx[ci])
|
|
|
|
| 1966 |
for hj, hk in h_to_heavy.items():
|
| 1967 |
heavy_to_h.setdefault(hk, []).append(hj)
|
| 1968 |
|
|
|
|
| 1969 |
PROT_DONOR_ATOMS = {
|
| 1970 |
"N","OG","OG1","OH","SG","NZ","NH1","NH2","NE",
|
| 1971 |
"ND1","NE2","NE1","ND2",
|
|
|
|
| 1979 |
HBOND_ANG_MIN = 120.0
|
| 1980 |
HBOND_PROXY = 90.0
|
| 1981 |
|
| 1982 |
+
results = []
|
| 1983 |
+
hbond_residues = set()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1984 |
|
| 1985 |
+
# ── H-BOND ────────────────────────────────────────────────────────────────
|
| 1986 |
polar_mask = np.array([
|
| 1987 |
r_el_arr[j] in ("N","O","S") and r_el_arr[j] != "H"
|
| 1988 |
and r_rn[j] not in ("HOH","WAT","DOD")
|
|
|
|
| 1997 |
if key in hbond_residues:
|
| 1998 |
continue
|
| 1999 |
|
| 2000 |
+
dists_j = np.linalg.norm(lxyz - rp, axis=1)
|
|
|
|
| 2001 |
|
|
|
|
| 2002 |
if an in PROT_DONOR_ATOMS:
|
| 2003 |
cand = np.where(lig_is_acceptor & (dists_j <= HBOND_DA_MAX))[0]
|
| 2004 |
if len(cand):
|
|
|
|
| 2006 |
for i in cand:
|
| 2007 |
d_DA = float(dists_j[i])
|
| 2008 |
if hs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2009 |
best = max(
|
| 2010 |
_angle3(rp, rc[hj], lxyz[i]) for hj in hs
|
| 2011 |
)
|
| 2012 |
if best < HBOND_ANG_MIN: continue
|
| 2013 |
else:
|
|
|
|
| 2014 |
nbs_i = [nb.GetIdx() for nb in latom[i].GetNeighbors()
|
| 2015 |
if nb.GetAtomicNum() != 1 and nb.GetIdx() < nl]
|
| 2016 |
if nbs_i:
|
|
|
|
| 2024 |
|
| 2025 |
if key in hbond_residues: continue
|
| 2026 |
|
|
|
|
| 2027 |
if an in PROT_ACCEPTOR_ATOMS:
|
| 2028 |
cand = np.where(lig_is_donor & (dists_j <= HBOND_DA_MAX))[0]
|
| 2029 |
if len(cand):
|
| 2030 |
for i in cand:
|
| 2031 |
d_DA = float(dists_j[i])
|
|
|
|
| 2032 |
lig_hs = [nb.GetIdx() for nb in latom[i].GetNeighbors()
|
| 2033 |
if nb.GetAtomicNum() == 1 and nb.GetIdx() < nl]
|
| 2034 |
if lig_hs:
|
|
|
|
| 2047 |
prot_el=el,is_donor=False,ring_atom_indices=None))
|
| 2048 |
break
|
| 2049 |
|
| 2050 |
+
# ── HYDROPHOBIC, IONIC, METAL ─────────────────────────────────────────────
|
|
|
|
|
|
|
| 2051 |
for j in range(nr):
|
| 2052 |
rn = r_rn[j]; ch = r_ch[j]; ri = int(r_ri[j]); el = r_el[j]; rp = rc[j]
|
| 2053 |
dists_j = np.linalg.norm(lxyz - rp, axis=1)
|
| 2054 |
md = float(dists_j.min()); mi = int(dists_j.argmin())
|
| 2055 |
if md > max(cutoff + 1.0, 5.6): continue
|
| 2056 |
|
| 2057 |
+
# Hydrophobic: extended to include heme residue names
|
| 2058 |
+
if el in {"C","S","CL","BR","I"} and rn in _HYDR_EXTENDED:
|
| 2059 |
cand = np.where(lig_is_hydrophobic & (dists_j < cutoff))[0]
|
| 2060 |
if len(cand):
|
| 2061 |
i = int(cand[0])
|
|
|
|
| 2076 |
itype="ionic",distance=round(float(dists_j[i]),1),
|
| 2077 |
lig_atom_idx=i,prot_el=el,is_donor=True,ring_atom_indices=None)); break
|
| 2078 |
|
| 2079 |
+
_is_heme_fe = (r_rn[j] in HEME_RESNAMES
|
| 2080 |
+
and r_an[j].strip().upper() == "FE")
|
| 2081 |
+
if rn.strip().upper() in _METALS_SET or el in _METALS_SET or _is_heme_fe:
|
| 2082 |
if md < 2.8:
|
| 2083 |
results.append(dict(resname=rn,chain=ch,resid=ri,
|
| 2084 |
itype="metal",distance=round(md,1),lig_atom_idx=mi,
|
| 2085 |
prot_el=el,is_donor=False,ring_atom_indices=None))
|
| 2086 |
|
| 2087 |
+
# ── π-π AND CATION-π (amino acids + heme porphyrin) ──────────────────────
|
|
|
|
|
|
|
| 2088 |
lr = _get_aromatic_ring_data(lig_mol_3d, conf)
|
| 2089 |
if lr:
|
| 2090 |
arom_mask = np.array([
|
|
|
|
| 2114 |
lig_atom_idx=ring_idxs[0],prot_el="N",is_donor=True,
|
| 2115 |
ring_atom_indices=ring_idxs)); break
|
| 2116 |
|
| 2117 |
+
# ── HALOGEN BOND ──────────────────────────────────────────────────────────
|
|
|
|
|
|
|
| 2118 |
_XD = {17:"CL", 35:"BR", 53:"I"}
|
| 2119 |
_XA_el = {"O","N","S","F"}
|
| 2120 |
|
|
|
|
| 2121 |
arom_C_mask = np.array([
|
| 2122 |
r_rn[j] in _AROM_ATOMS and r_an[j] in _AROM_ATOM_NAMES and r_el[j] == "C"
|
| 2123 |
for j in range(nr)
|
|
|
|
| 2133 |
if c_nb is None: continue
|
| 2134 |
c_pos = lxyz[c_nb]
|
| 2135 |
|
| 2136 |
+
max_d = vdw_x + 1.98 + 0.5
|
|
|
|
| 2137 |
cand_mask = xb_acc_mask & (np.linalg.norm(rc - xp, axis=1) <= max_d)
|
| 2138 |
cand_idx = np.where(cand_mask)[0]
|
| 2139 |
if not len(cand_idx): continue
|
| 2140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2141 |
for j in cand_idx:
|
| 2142 |
ael = r_el[j]; ap = rc[j]
|
| 2143 |
vdw_sum = vdw_x + _VDW.get(ael, 1.70) + 0.5
|
|
|
|
| 2145 |
if d > vdw_sum: continue
|
| 2146 |
ang1 = _angle3(c_pos, xp, ap)
|
| 2147 |
if ang1 < 140.0: continue
|
|
|
|
| 2148 |
r_nbs = [k for k in range(nr)
|
| 2149 |
if k != j and r_el[k] != "H"
|
| 2150 |
and float(np.linalg.norm(rc[k] - ap)) < 1.85]
|
|
|
|
| 2154 |
itype="halogen",distance=round(d,1),lig_atom_idx=i,
|
| 2155 |
prot_el=ael,is_donor=False,ring_atom_indices=None))
|
| 2156 |
|
| 2157 |
+
# ── H-BOND TO HALOGEN ─────────────────────────────────────────────────────
|
|
|
|
|
|
|
| 2158 |
_HA = {9:"F", 17:"CL", 35:"BR", 53:"I"}
|
| 2159 |
_HD = {"O","N","S"}
|
| 2160 |
|
| 2161 |
if len(h_idx):
|
| 2162 |
+
h_coords = rc[h_idx]
|
| 2163 |
for i in range(nl):
|
| 2164 |
ano = latom[i].GetAtomicNum()
|
| 2165 |
if ano not in _HA: continue
|
|
|
|
| 2168 |
if nb.GetIdx() < nl), None)
|
| 2169 |
if c_nb2 is None: continue
|
| 2170 |
c_pos2 = lxyz[c_nb2]
|
| 2171 |
+
dhx_all = np.linalg.norm(h_coords - xp, axis=1)
|
|
|
|
| 2172 |
close_h = np.where(dhx_all <= _VDW["H"] + vdw_x)[0]
|
| 2173 |
for kk in close_h:
|
| 2174 |
hj = int(h_idx[kk]); hp = rc[hj]; dhx = float(dhx_all[kk])
|
|
|
|
| 2183 |
|
| 2184 |
return results
|
| 2185 |
|
| 2186 |
+
|
| 2187 |
def _deduplicate_interactions(interactions: list) -> list:
|
| 2188 |
priority={t:i for i,t in enumerate(_ITYPE_PRIORITY)}
|
| 2189 |
best:dict={}
|
|
|
|
| 2197 |
|
| 2198 |
|
| 2199 |
def _enrich_with_res_xyz(interactions, mol3d, receptor_pdb):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2200 |
import numpy as np
|
| 2201 |
from prody import parsePDB
|
| 2202 |
try:
|
|
|
|
| 2219 |
lai = ix.get("lig_atom_idx", 0)
|
| 2220 |
lai = min(lai, n_lig - 1)
|
| 2221 |
|
|
|
|
|
|
|
| 2222 |
ring_idxs = ix.get("ring_atom_indices") or []
|
| 2223 |
if ring_idxs:
|
| 2224 |
valid = [i for i in ring_idxs if 0 <= i < n_lig]
|
|
|
|
| 2230 |
lig_anchor = lxyz[lai]
|
| 2231 |
ix["lig_anchor_xyz"] = lig_anchor.tolist()
|
| 2232 |
|
|
|
|
|
|
|
| 2233 |
res_idx = [j for j in range(len(rc))
|
| 2234 |
if rch[j].strip() == ch and int(rri[j]) == ri]
|
| 2235 |
if not res_idx:
|
| 2236 |
+
ix["res_xyz"] = lig_anchor.tolist()
|
| 2237 |
continue
|
| 2238 |
|
|
|
|
|
|
|
| 2239 |
res_coords = rc[res_idx]
|
| 2240 |
dists = np.linalg.norm(res_coords - lig_anchor, axis=1)
|
| 2241 |
closest_local = int(dists.argmin())
|
|
|
|
| 2255 |
|
| 2256 |
|
| 2257 |
def _ring_centroid_2d(ring_atom_indices, svg_coords):
|
|
|
|
| 2258 |
xs=[svg_coords[i][0] for i in ring_atom_indices if i in svg_coords]
|
| 2259 |
ys=[svg_coords[i][1] for i in ring_atom_indices if i in svg_coords]
|
| 2260 |
if not xs: return None, None
|
|
|
|
| 2262 |
|
| 2263 |
|
| 2264 |
def _ring_centroid_from_atom(mol2d, atom_idx_2d, svg_coords):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2265 |
ring_info = mol2d.GetRingInfo()
|
| 2266 |
best_ring = None
|
| 2267 |
best_size = 999
|
| 2268 |
for ring in ring_info.AtomRings():
|
| 2269 |
if atom_idx_2d in ring:
|
|
|
|
| 2270 |
if mol2d.GetAtomWithIdx(ring[0]).GetIsAromatic():
|
| 2271 |
if len(ring) < best_size:
|
| 2272 |
best_ring = ring
|
|
|
|
| 2281 |
|
| 2282 |
|
| 2283 |
def _place_residues_no_cross(interactions, svg_coords, cx, cy, R=210):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2284 |
if not interactions: return []
|
| 2285 |
|
|
|
|
| 2286 |
items = []
|
| 2287 |
for ix in interactions:
|
| 2288 |
if ix.get("ring_atom_indices"):
|
|
|
|
| 2295 |
angle = _math.atan2(ay - cy, ax - cx)
|
| 2296 |
items.append({**ix, "angle": angle, "anchor_angle": angle})
|
| 2297 |
|
|
|
|
| 2298 |
items.sort(key=lambda x: x["angle"])
|
| 2299 |
n = len(items)
|
| 2300 |
if n == 1:
|
|
|
|
| 2304 |
"by": cy + R * _math.sin(a),
|
| 2305 |
"slot_angle": a}]
|
| 2306 |
|
|
|
|
|
|
|
|
|
|
| 2307 |
for i in range(n):
|
| 2308 |
for j in range(i + 1, n):
|
| 2309 |
if abs(items[j]["angle"] - items[i]["angle"]) < 0.001:
|
| 2310 |
+
items[j]["angle"] += 0.05 * (j - i)
|
| 2311 |
|
|
|
|
|
|
|
|
|
|
| 2312 |
min_dist_px = 78.0
|
| 2313 |
|
|
|
|
|
|
|
|
|
|
| 2314 |
for _ in range(500):
|
| 2315 |
delta = [0.0] * n
|
| 2316 |
any_overlap = False
|
|
|
|
| 2326 |
|
| 2327 |
if dist < min_dist_px:
|
| 2328 |
overlap_px = min_dist_px - dist
|
|
|
|
| 2329 |
push_angle = overlap_px / max(R, 1.0)
|
|
|
|
|
|
|
| 2330 |
delta[i] -= push_angle * 0.5
|
| 2331 |
delta[j] += push_angle * 0.5
|
| 2332 |
any_overlap = True
|
|
|
|
| 2337 |
if not any_overlap:
|
| 2338 |
break
|
| 2339 |
|
|
|
|
| 2340 |
result = []
|
| 2341 |
for item in items:
|
| 2342 |
a = item["angle"]
|
|
|
|
| 2351 |
return result
|
| 2352 |
|
| 2353 |
|
| 2354 |
+
# ── Radial-collapse layout helpers ───────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2355 |
|
| 2356 |
def _rl_ligand_center(svg_coords):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2357 |
pts = list(svg_coords.values())
|
| 2358 |
if not pts:
|
| 2359 |
return 400.0, 380.0
|
|
|
|
| 2363 |
|
| 2364 |
|
| 2365 |
def _rl_anchor_angle(ix, svg_coords, cx, cy):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2366 |
ai = ix.get("lig_atom_idx", 0)
|
| 2367 |
ax, ay = svg_coords.get(ai, (cx, cy))
|
| 2368 |
ring_idxs = ix.get("ring_atom_indices")
|
|
|
|
| 2374 |
|
| 2375 |
|
| 2376 |
def _rl_ray_boundary(cx, cy, theta, atom_xy, atom_r=20.0):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2377 |
dx = _math.cos(theta)
|
| 2378 |
dy = _math.sin(theta)
|
| 2379 |
r2 = atom_r * atom_r
|
|
|
|
| 2382 |
vx = ax - cx
|
| 2383 |
vy = ay - cy
|
| 2384 |
t_proj = vx * dx + vy * dy
|
| 2385 |
+
if t_proj < -atom_r:
|
| 2386 |
continue
|
| 2387 |
perp2 = vx * vx + vy * vy - t_proj * t_proj
|
| 2388 |
+
if perp2 >= r2:
|
| 2389 |
continue
|
| 2390 |
t_exit = t_proj + _math.sqrt(max(r2 - perp2, 0.0))
|
| 2391 |
if t_exit > t_max:
|
| 2392 |
t_max = t_exit
|
| 2393 |
+
return t_max if t_max > 1.0 else 20.0
|
| 2394 |
|
| 2395 |
|
| 2396 |
def _rl_place_radially(sorted_interactions, svg_coords, cx, cy,
|
| 2397 |
atom_xy, atom_r, gap, node_r, rng):
|
| 2398 |
+
JITTER_T = 7.0
|
| 2399 |
+
JITTER_R = 4.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2400 |
|
|
|
|
| 2401 |
n = len(sorted_interactions)
|
| 2402 |
jit_t = rng.uniform(-JITTER_T, JITTER_T, n)
|
| 2403 |
jit_r = rng.uniform(-JITTER_R, JITTER_R, n)
|
|
|
|
| 2410 |
|
| 2411 |
cos_t = _math.cos(theta)
|
| 2412 |
sin_t = _math.sin(theta)
|
|
|
|
| 2413 |
tx, ty = -sin_t, cos_t
|
| 2414 |
|
| 2415 |
bx = cx + r_place * cos_t + jit_t[k] * tx
|
|
|
|
| 2421 |
|
| 2422 |
def _rl_resolve_overlaps(positions, atom_xy, cx, cy,
|
| 2423 |
node_r=24.55, excl_r=46.0, max_iters=400):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2424 |
n = len(positions)
|
| 2425 |
if n <= 1:
|
| 2426 |
return list(positions)
|
| 2427 |
|
| 2428 |
+
min_sep = node_r * 2.0 + 8.0
|
| 2429 |
|
| 2430 |
bx = [p[0] for p in positions]
|
| 2431 |
by = [p[1] for p in positions]
|
| 2432 |
|
|
|
|
|
|
|
| 2433 |
for i in range(n):
|
| 2434 |
for j in range(i + 1, n):
|
| 2435 |
ddx = bx[j] - bx[i]; ddy = by[j] - by[i]
|
|
|
|
| 2440 |
bx[j] += _math.cos(ang) * kick; by[j] += _math.sin(ang) * kick
|
| 2441 |
|
| 2442 |
for _it in range(max_iters):
|
|
|
|
| 2443 |
dx_acc = [0.0] * n
|
| 2444 |
dy_acc = [0.0] * n
|
| 2445 |
any_overlap = False
|
|
|
|
| 2459 |
bx[i] += dx_acc[i]
|
| 2460 |
by[i] += dy_acc[i]
|
| 2461 |
|
|
|
|
| 2462 |
for i in range(n):
|
| 2463 |
for (ax, ay) in atom_xy:
|
| 2464 |
ddx = bx[i] - ax
|
|
|
|
| 2466 |
d = _math.sqrt(ddx * ddx + ddy * ddy) + 1e-8
|
| 2467 |
if d < excl_r:
|
| 2468 |
push = (excl_r - d) * 0.5 / d
|
|
|
|
| 2469 |
if d < 0.5:
|
| 2470 |
ddx = bx[i] - cx
|
| 2471 |
ddy = by[i] - cy
|
|
|
|
| 2481 |
|
| 2482 |
|
| 2483 |
def _rl_reduce_crossings(ix_list, bx_by, svg_coords, cx, cy):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2484 |
n = len(ix_list)
|
| 2485 |
bx_by = list(bx_by)
|
| 2486 |
|
|
|
|
| 2495 |
return (ax, ay)
|
| 2496 |
|
| 2497 |
def _cross(a1, b1, a2, b2):
|
|
|
|
| 2498 |
def _side(O, A, B):
|
| 2499 |
return (B[0]-O[0])*(A[1]-O[1]) - (B[1]-O[1])*(A[0]-O[0])
|
| 2500 |
d1 = _side(a2, b2, a1); d2 = _side(a2, b2, b1)
|
|
|
|
| 2516 |
|
| 2517 |
|
| 2518 |
def _place_residues_pca(interactions, svg_coords, mol3d, cx, cy, R=210):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2519 |
if not interactions:
|
| 2520 |
return []
|
| 2521 |
|
| 2522 |
try:
|
| 2523 |
import numpy as _np_rc
|
| 2524 |
|
| 2525 |
+
NODE_R = 24.55
|
| 2526 |
+
GAP = 45.0
|
| 2527 |
+
ATOM_R = 20.0
|
| 2528 |
|
|
|
|
| 2529 |
lx, ly = _rl_ligand_center(svg_coords)
|
| 2530 |
atom_xy = list(svg_coords.values())
|
| 2531 |
|
|
|
|
| 2532 |
anchor_a = [_rl_anchor_angle(ix, svg_coords, lx, ly)
|
| 2533 |
for ix in interactions]
|
| 2534 |
order = sorted(range(len(interactions)),
|
| 2535 |
key=lambda k: anchor_a[k])
|
| 2536 |
sorted_ix = [interactions[k] for k in order]
|
| 2537 |
|
|
|
|
| 2538 |
rng = _np_rc.random.default_rng(42)
|
| 2539 |
positions = _rl_place_radially(
|
| 2540 |
sorted_ix, svg_coords, lx, ly,
|
| 2541 |
atom_xy, ATOM_R, GAP, NODE_R, rng,
|
| 2542 |
)
|
| 2543 |
|
|
|
|
| 2544 |
positions = _rl_resolve_overlaps(
|
| 2545 |
positions, atom_xy, lx, ly,
|
| 2546 |
node_r=NODE_R,
|
| 2547 |
+
excl_r=NODE_R + ATOM_R,
|
| 2548 |
)
|
| 2549 |
|
|
|
|
| 2550 |
positions = _rl_reduce_crossings(
|
| 2551 |
sorted_ix, positions, svg_coords, lx, ly,
|
| 2552 |
)
|
| 2553 |
|
|
|
|
| 2554 |
result = []
|
| 2555 |
for k, (bx, by) in enumerate(positions):
|
| 2556 |
ang = _math.atan2(by - ly, bx - lx)
|
|
|
|
| 2566 |
except Exception:
|
| 2567 |
return _place_residues_no_cross(interactions, svg_coords, cx, cy, R)
|
| 2568 |
|
| 2569 |
+
|
| 2570 |
def _render_ligand_svg(mol2d, svg_coords):
|
| 2571 |
from rdkit import Chem
|
| 2572 |
parts=[]
|
|
|
|
| 2597 |
f' stroke="#1a1a1a" stroke-width="1.77" opacity="0.9"/>')
|
| 2598 |
elif bt==Chem.BondType.DOUBLE:
|
| 2599 |
dx,dy=x2s-x1s,y2s-y1s; L=_math.sqrt(dx*dx+dy*dy)+1e-9
|
| 2600 |
+
px,py=-dy/L*2.5,dx/L*2.5
|
| 2601 |
for sg in (1,-1):
|
| 2602 |
parts.append(f'<line x1="{x1s+px*sg:.2f}" y1="{y1s+py*sg:.2f}"'
|
| 2603 |
f' x2="{x2s+px*sg:.2f}" y2="{y2s+py*sg:.2f}"'
|
|
|
|
| 2613 |
bd=bond.GetBondDir()
|
| 2614 |
if bd==Chem.BondDir.BEGINWEDGE:
|
| 2615 |
dx,dy=x2s-x1s,y2s-y1s; L=_math.sqrt(dx*dx+dy*dy)+1e-9
|
| 2616 |
+
px,py=-dy/L*3.0,dx/L*3.0
|
| 2617 |
parts.append(f'<polygon points="{x1s:.2f},{y1s:.2f}'
|
| 2618 |
f' {x2s+px:.2f},{y2s+py:.2f} {x2s-px:.2f},{y2s-py:.2f}"'
|
| 2619 |
f' fill="#1a1a1a" stroke="none"/>')
|
|
|
|
| 2629 |
parts.append(f'<line x1="{x1s:.2f}" y1="{y1s:.2f}" x2="{x2s:.2f}" y2="{y2s:.2f}"'
|
| 2630 |
f' stroke="#1a1a1a" stroke-width="1.77" opacity="0.9"/>')
|
| 2631 |
|
|
|
|
| 2632 |
for ring in arom_rings:
|
| 2633 |
rcoords=[svg_coords.get(i,(0,0)) for i in ring]
|
| 2634 |
rcx=sum(x for x,y in rcoords)/len(rcoords)
|
|
|
|
| 2641 |
parts.append(f'<circle cx="{rcx:.2f}" cy="{rcy:.2f}" r="5.43"'
|
| 2642 |
f' fill="{_AROM_DOT_CLR}"/>')
|
| 2643 |
|
|
|
|
| 2644 |
for i in range(mol2d.GetNumAtoms()):
|
| 2645 |
atom=mol2d.GetAtomWithIdx(i); sym=atom.GetSymbol()
|
| 2646 |
if sym=="C": continue
|
| 2647 |
ax,ay=svg_coords.get(i,(0,0))
|
| 2648 |
clr=_ATOM_CLR.get(sym.upper(),"#555")
|
| 2649 |
+
fs={"H":16}.get(sym,17.65)
|
| 2650 |
hw={"H":7,"N":9,"O":9,"S":11,"P":11,"F":8,"CL":16,"BR":16,"I":11}.get(sym.upper(),9)
|
| 2651 |
parts.append(f'<rect x="{ax-hw:.1f}" y="{ay-11:.1f}"'
|
| 2652 |
f' width="{hw*2:.0f}" height="22" fill="white" stroke="none"/>')
|
|
|
|
| 2663 |
return "".join(parts)
|
| 2664 |
|
| 2665 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2666 |
def _render_diagram_svg(mol2d, svg_coords, placements, title, W, H):
|
| 2667 |
parts=[]
|
| 2668 |
parts.append(f'<svg width="100%" viewBox="0 0 {W} {H}" xmlns="http://www.w3.org/2000/svg">')
|
| 2669 |
parts.append(f'<rect width="{W}" height="{H}" fill="white"/>')
|
| 2670 |
|
|
|
|
| 2671 |
if title:
|
| 2672 |
esc=title.replace("&","&").replace("<","<").replace(">",">")
|
| 2673 |
tw=len(esc)*14.5+48; tw=max(tw,240); tw=min(tw,W-40)
|
|
|
|
| 2679 |
f' font-family="Arial,sans-serif" font-size="24.93"'
|
| 2680 |
f' font-weight="700" fill="#1a1a1a">{esc}</text>')
|
| 2681 |
|
|
|
|
| 2682 |
for p in placements:
|
| 2683 |
itype=p["itype"]
|
| 2684 |
bx,by=p["bx"],p["by"]
|
|
|
|
| 2687 |
parts.append(f'<circle cx="{cbx:.1f}" cy="{cby:.1f}" r="24.55"'
|
| 2688 |
f' fill="{bg["fill"]}" opacity="{bg["opacity"]}"/>')
|
| 2689 |
|
|
|
|
| 2690 |
for p in placements:
|
| 2691 |
itype=p["itype"]
|
| 2692 |
+
if itype=="hydrophobic": continue
|
| 2693 |
|
| 2694 |
bx,by=p["bx"],p["by"]
|
| 2695 |
cbx=max(50,min(bx,W-50)); cby=max(70,min(by,H-65))
|
| 2696 |
|
|
|
|
| 2697 |
if itype in ("pi_pi","cation_pi") and p.get("ring_atom_indices"):
|
| 2698 |
lx,ly=_ring_centroid_2d(p["ring_atom_indices"],svg_coords)
|
| 2699 |
if lx is None:
|
|
|
|
| 2706 |
dash_attr_hbx=' stroke-dasharray="4 2 1 2"'
|
| 2707 |
|
| 2708 |
if itype in ("pi_pi","cation_pi"):
|
|
|
|
| 2709 |
parts.append(f'<line x1="{lx:.2f}" y1="{ly:.2f}"'
|
| 2710 |
f' x2="{cbx:.2f}" y2="{cby:.2f}"'
|
| 2711 |
f' stroke="{clr}" stroke-width="1.6"'
|
| 2712 |
f'{dash_attr} opacity="0.85"/>')
|
| 2713 |
elif itype in ("hbond","hbond_to_halogen"):
|
|
|
|
| 2714 |
da=dash_attr if itype=="hbond" else dash_attr_hbx
|
| 2715 |
parts.append(f'<line x1="{lx:.2f}" y1="{ly:.2f}"'
|
| 2716 |
f' x2="{cbx:.2f}" y2="{cby:.2f}"'
|
| 2717 |
f' stroke="{clr}" stroke-width="1.6"'
|
| 2718 |
f'{da} opacity="0.85"/>')
|
|
|
|
|
|
|
| 2719 |
if p.get("distance") is not None:
|
|
|
|
| 2720 |
t_along = 0.40
|
| 2721 |
bx_l = lx + (cbx - lx) * t_along
|
| 2722 |
by_l = ly + (cby - ly) * t_along
|
|
|
|
| 2723 |
dx_l = cbx - lx; dy_l = cby - ly
|
| 2724 |
_len = _math.sqrt(dx_l*dx_l + dy_l*dy_l) + 1e-9
|
| 2725 |
+
px_l = -dy_l / _len; py_l = dx_l / _len
|
|
|
|
| 2726 |
mx2 = bx_l + px_l * 14
|
| 2727 |
my2 = by_l + py_l * 14
|
| 2728 |
ds=f"{p['distance']}\u00c5"
|
|
|
|
| 2735 |
f' font-family="Arial,sans-serif" font-size="14"'
|
| 2736 |
f' font-weight="700" fill="{clr}">{ds}</text>')
|
| 2737 |
else:
|
|
|
|
| 2738 |
da={"ionic":"6 2 2 2","metal":"3 2","halogen":"5 2"}.get(itype,"5 3")
|
| 2739 |
parts.append(f'<line x1="{lx:.2f}" y1="{ly:.2f}"'
|
| 2740 |
f' x2="{cbx:.2f}" y2="{cby:.2f}"'
|
|
|
|
| 2758 |
f' font-family="Arial,sans-serif" font-size="14"'
|
| 2759 |
f' font-weight="700" fill="{clr}">{ds}</text>')
|
| 2760 |
|
|
|
|
| 2761 |
parts.append(_render_ligand_svg(mol2d, svg_coords))
|
| 2762 |
|
|
|
|
| 2763 |
for p in placements:
|
| 2764 |
itype=p["itype"]
|
| 2765 |
bx,by=p["bx"],p["by"]
|
| 2766 |
cbx=max(50,min(bx,W-50)); cby=max(70,min(by,H-65))
|
| 2767 |
rn=p["resname"]; ri=p["resid"]; ch=p.get("chain","")
|
| 2768 |
+
_NO_NUM = HEME_RESNAMES | METAL_RESNAMES
|
| 2769 |
+
lbl = rn.upper() if rn.upper() in _NO_NUM else f"{rn.upper()} {ri}{ch}"
|
| 2770 |
lbl_clr=_LBL_CLR.get(itype,"#333")
|
|
|
|
| 2771 |
parts.append(f'<text x="{cbx:.1f}" y="{cby:.1f}" text-anchor="middle"'
|
| 2772 |
f' dominant-baseline="central"'
|
| 2773 |
f' font-family="Arial,sans-serif" font-size="14.29"'
|
| 2774 |
f' font-weight="700" fill="{lbl_clr}">{lbl}</text>')
|
| 2775 |
|
|
|
|
|
|
|
|
|
|
| 2776 |
_LEG_ORDER=["hydrophobic","hbond","pi_pi","cation_pi",
|
| 2777 |
"hbond_to_halogen","ionic","metal","halogen"]
|
| 2778 |
_LEG_LABEL={"hydrophobic":"Hydrophobic","hbond":"Hydrogen bond",
|
|
|
|
| 2782 |
active=[t for t in _LEG_ORDER if any(p["itype"]==t for p in placements)]
|
| 2783 |
if active:
|
| 2784 |
ly0 = H - 52
|
|
|
|
| 2785 |
def _entry_w(t):
|
| 2786 |
txt = _LEG_LABEL.get(t, t)
|
| 2787 |
return 9.54*2 + (4+28 if t != "hydrophobic" else 0) + 6 + len(txt)*9.5 + 20
|
|
|
|
| 2792 |
f' height="44" fill="white" stroke="#e0e0e0"'
|
| 2793 |
f' stroke-width="0.8" rx="6"/>')
|
| 2794 |
for k,it in enumerate(active):
|
|
|
|
|
|
|
|
|
|
| 2795 |
bg = _RES_CIRCLE.get(it, dict(fill="#ccc", opacity=0.2))
|
| 2796 |
+
clr = _LINE_CLR.get(it, bg["fill"])
|
| 2797 |
lbl = _LEG_LABEL.get(it, it)
|
|
|
|
|
|
|
| 2798 |
text_w = len(lbl) * 9.5 + 6
|
| 2799 |
glyph_w = 9.54*2 + (4 + 28 if it != "hydrophobic" else 0)
|
| 2800 |
entry_w = glyph_w + 6 + text_w
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2801 |
circ_cx = lx0 + sum(
|
| 2802 |
(9.54*2 + (4+28 if active[kk]!="hydrophobic" else 0) + 6 + len(_LEG_LABEL.get(active[kk],active[kk]))*9.5 + 6 + 20)
|
| 2803 |
for kk in range(k)
|
| 2804 |
) + 9.54
|
| 2805 |
parts.append(f'<circle cx="{circ_cx:.1f}" cy="{ly0+10}" r="9.54"'
|
| 2806 |
f' fill="{bg["fill"]}" opacity="{bg["opacity"]}"/>')
|
|
|
|
|
|
|
| 2807 |
line_x1 = circ_cx + 9.54 + 4
|
| 2808 |
line_x2 = line_x1 + 28
|
| 2809 |
if it != "hydrophobic":
|
|
|
|
| 2811 |
f' x2="{line_x2:.1f}" y2="{ly0+10}"'
|
| 2812 |
f' stroke="{clr}" stroke-width="2"'
|
| 2813 |
f' stroke-dasharray="5 3" opacity="0.85"/>')
|
|
|
|
|
|
|
| 2814 |
text_x = (line_x2 if it != "hydrophobic" else circ_cx + 9.54) + 6
|
| 2815 |
parts.append(f'<text x="{text_x:.1f}" y="{ly0+10}" text-anchor="start"'
|
| 2816 |
f' dominant-baseline="central"'
|
|
|
|
| 2834 |
size: tuple = (800, 759),
|
| 2835 |
max_residues: int = 14,
|
| 2836 |
) -> bytes:
|
| 2837 |
+
"""2D interaction diagram — SVG bytes."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2838 |
try:
|
| 2839 |
mol2d, sc, pl, W, H = _build_diagram_data(
|
| 2840 |
receptor_pdb, pose_sdf, smiles, cutoff, max_residues, size
|
|
|
|
| 2850 |
return svg.encode()
|
| 2851 |
|
| 2852 |
|
|
|
|
| 2853 |
def draw_interaction_diagram_data(
|
| 2854 |
receptor_pdb: str,
|
| 2855 |
pose_sdf: str,
|
|
|
|
| 2859 |
size: tuple = (800, 759),
|
| 2860 |
max_residues: int = 14,
|
| 2861 |
) -> dict:
|
| 2862 |
+
"""Same pipeline as draw_interaction_diagram but returns a dict for interactive renderer."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2863 |
from rdkit import Chem, RDLogger
|
| 2864 |
from rdkit.Chem import rdDepictor
|
| 2865 |
RDLogger.DisableLog("rdApp.*")
|
|
|
|
| 2902 |
try: raw = _detect_all_interactions(mol3d, receptor_pdb, cutoff=cutoff)
|
| 2903 |
except: raw = []
|
| 2904 |
|
|
|
|
|
|
|
| 2905 |
try: _enrich_with_res_xyz(raw, mol3d, receptor_pdb)
|
| 2906 |
except: pass
|
| 2907 |
|
|
|
|
| 2917 |
|
| 2918 |
cx, cy = W // 2, H // 2
|
| 2919 |
sc = _compute_svg_coords(mol2d, cx, cy, target_size=280)
|
|
|
|
| 2920 |
pl = _place_residues_pca(ded, sc, mol3d, cx, cy, R=210)
|
| 2921 |
|
|
|
|
| 2922 |
lig_svg = _render_ligand_svg(mol2d, sc)
|
|
|
|
|
|
|
| 2923 |
sc_serial = {str(k): [round(v[0], 2), round(v[1], 2)] for k, v in sc.items()}
|
| 2924 |
|
| 2925 |
+
import json as _json
|
| 2926 |
pl_serial = []
|
| 2927 |
for p in pl:
|
| 2928 |
lx, ly = sc.get(p.get("lig_atom_idx", 0), (cx, cy))
|
|
|
|
| 2932 |
lx, ly = rx, ry
|
| 2933 |
pl_serial.append({
|
| 2934 |
"id": f"r{len(pl_serial)}",
|
| 2935 |
+
"label": (p['resname'].upper() if p['resname'].upper() in (HEME_RESNAMES | METAL_RESNAMES)
|
| 2936 |
+
else f"{p['resname']} {p['resid']}{p.get('chain','')}"),
|
| 2937 |
"itype": p["itype"],
|
| 2938 |
"distance": p.get("distance"),
|
| 2939 |
+
"lx": round(lx, 2),
|
| 2940 |
+
"ly": round(ly, 2),
|
| 2941 |
+
"bx": round(p["bx"], 2),
|
| 2942 |
+
"by": round(p["by"], 2),
|
| 2943 |
})
|
| 2944 |
|
| 2945 |
RDLogger.EnableLog("rdApp.error")
|
|
|
|
| 2953 |
|
| 2954 |
def _build_diagram_data(receptor_pdb, pose_sdf, smiles, cutoff, max_residues,
|
| 2955 |
size=(800, 759)):
|
| 2956 |
+
"""Shared setup for both static SVG and interactive HTML renderers."""
|
|
|
|
|
|
|
|
|
|
| 2957 |
from rdkit import Chem, RDLogger
|
| 2958 |
from rdkit.Chem import rdDepictor
|
| 2959 |
RDLogger.DisableLog("rdApp.*")
|
|
|
|
| 2990 |
try: raw = _detect_all_interactions(mol3d, receptor_pdb, cutoff=cutoff)
|
| 2991 |
except: raw = []
|
| 2992 |
|
|
|
|
|
|
|
| 2993 |
try: _enrich_with_res_xyz(raw, mol3d, receptor_pdb)
|
| 2994 |
except: pass
|
| 2995 |
|
|
|
|
| 3003 |
ded = ded[:max_residues]
|
| 3004 |
cx, cy = W // 2, H // 2
|
| 3005 |
sc = _compute_svg_coords(mol2d, cx, cy, target_size=280)
|
|
|
|
| 3006 |
pl = _place_residues_pca(ded, sc, mol3d, cx, cy, R=210)
|
| 3007 |
RDLogger.EnableLog("rdApp.error")
|
| 3008 |
return mol2d, sc, pl, W, H
|
|
|
|
| 3017 |
size: tuple = (800, 759),
|
| 3018 |
max_residues: int = 14,
|
| 3019 |
) -> str:
|
| 3020 |
+
"""Interactive HTML version of draw_interaction_diagram."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3021 |
import json
|
| 3022 |
|
| 3023 |
try:
|
|
|
|
| 3027 |
except Exception as e:
|
| 3028 |
return f'<p style="color:red">Error: {e}</p>'
|
| 3029 |
|
|
|
|
| 3030 |
lig_svg = _render_ligand_svg(mol2d, sc)
|
| 3031 |
|
|
|
|
| 3032 |
residues_js = []
|
| 3033 |
for p in pl:
|
| 3034 |
itype = p["itype"]
|
| 3035 |
ai = p.get("lig_atom_idx", 0)
|
| 3036 |
lx, ly = sc.get(ai, (W // 2, H // 2))
|
|
|
|
| 3037 |
if itype in ("pi_pi", "cation_pi") and p.get("ring_atom_indices"):
|
| 3038 |
rx, ry = _ring_centroid_2d(p["ring_atom_indices"], sc)
|
| 3039 |
if rx is not None: lx, ly = rx, ry
|
| 3040 |
residues_js.append({
|
| 3041 |
"id": p["resname"] + str(p["resid"]) + p.get("chain",""),
|
| 3042 |
+
"label": (p['resname'].upper() if p['resname'].upper() in (HEME_RESNAMES | METAL_RESNAMES)
|
| 3043 |
+
else f"{p['resname']} {p['resid']}{p.get('chain','')}"),
|
| 3044 |
"itype": itype,
|
| 3045 |
"dist": str(p["distance"]) + "Å" if p.get("distance") else "",
|
| 3046 |
"lx": round(lx, 2),
|
|
|
|
| 3049 |
"by": round(p["by"], 2),
|
| 3050 |
})
|
| 3051 |
|
|
|
|
| 3052 |
legend_types = list(dict.fromkeys(p["itype"] for p in pl))
|
| 3053 |
_LEG_LABEL = {
|
| 3054 |
"hbond":"H-bond", "hbond_to_halogen":"H···Halogen",
|
|
|
|
| 3057 |
"metal":"Metal","halogen":"Halogen bond",
|
| 3058 |
}
|
| 3059 |
|
|
|
|
| 3060 |
esc_title = (title.replace("&","&").replace("<","<").replace(">",">"))
|
| 3061 |
tw = min(len(esc_title) * 14 + 48, W - 40)
|
| 3062 |
pill_x = (W - tw) / 2
|
|
|
|
| 3122 |
const gLeg = document.getElementById("g-legend");
|
| 3123 |
|
| 3124 |
let pos = {{}};
|
| 3125 |
+
let els = {{}};
|
| 3126 |
|
| 3127 |
function ns(tag){{ return document.createElementNS("http://www.w3.org/2000/svg",tag); }}
|
| 3128 |
function attr(el,obj){{ for(const[k,v] of Object.entries(obj)) el.setAttribute(k,v); return el; }}
|
|
|
|
| 3144 |
drawLegend();
|
| 3145 |
}}
|
| 3146 |
|
| 3147 |
+
function distLabel(r){{
|
| 3148 |
const cfg=TYPE_CFG[r.itype]||TYPE_CFG.hbond;
|
| 3149 |
if(!r.dist||!cfg.line) return null;
|
| 3150 |
const p=pos[r.id];
|
|
|
|
| 3165 |
|
| 3166 |
const grp=ns("g"); grp.setAttribute("class","r-circle"); grp.setAttribute("data-id",r.id);
|
| 3167 |
|
|
|
|
| 3168 |
let lineEl=null, drectEl=null, dtxtEl=null;
|
| 3169 |
if(cfg.line){{
|
| 3170 |
lineEl=attr(ns("line"),{{x1:r.lx,y1:r.ly,x2:p.x,y2:p.y,
|
|
|
|
| 3185 |
}}
|
| 3186 |
}}
|
| 3187 |
|
|
|
|
| 3188 |
const circ=attr(ns("circle"),{{cx:p.x,cy:p.y,r:24.55,fill:cfg.fill,opacity:0.2,
|
| 3189 |
stroke:cfg.stroke,"stroke-width":1.2}});
|
| 3190 |
grp.appendChild(circ);
|
| 3191 |
|
|
|
|
| 3192 |
const txt=attr(ns("text"),{{x:p.x,y:p.y,"text-anchor":"middle",
|
| 3193 |
"dominant-baseline":"central","font-family":"Arial,sans-serif",
|
| 3194 |
"font-size":11,"font-weight":700,fill:lclr}});
|
|
|
|
| 3203 |
function updateResidue(r){{
|
| 3204 |
const p=pos[r.id];
|
| 3205 |
const e=els[r.id]; if(!e) return;
|
|
|
|
| 3206 |
e.circ.setAttribute("cx",p.x); e.circ.setAttribute("cy",p.y);
|
| 3207 |
e.txt.setAttribute("x",p.x); e.txt.setAttribute("y",p.y);
|
| 3208 |
if(e.lineEl){{ e.lineEl.setAttribute("x2",p.x); e.lineEl.setAttribute("y2",p.y); }}
|
|
|
|
| 3247 |
|
| 3248 |
function drawLegend(){{
|
| 3249 |
const ly0=H-48;
|
|
|
|
| 3250 |
const entries=LEG_TYPES.map(t=>{{
|
| 3251 |
const cfg=TYPE_CFG[t]||TYPE_CFG.hbond;
|
| 3252 |
const lbl=LEG_LABEL[t]||t;
|
|
|
|
| 3256 |
}});
|
| 3257 |
const total=entries.reduce((s,e)=>s+e.w,0);
|
| 3258 |
let cx2=(W-total)/2;
|
|
|
|
|
|
|
| 3259 |
const box=attr(ns("rect"),{{x:cx2-8,y:ly0-6,width:total+16,height:42,
|
| 3260 |
fill:"white",stroke:"#e0e0e0","stroke-width":0.8,rx:6}});
|
| 3261 |
gLeg.appendChild(box);
|
|
|
|
| 3292 |
|
| 3293 |
window.exportPNG=function(){{
|
| 3294 |
const scale=parseInt(document.getElementById("dpi-sel").value)||2;
|
|
|
|
| 3295 |
const clone=svg.cloneNode(true);
|
| 3296 |
clone.setAttribute("xmlns","http://www.w3.org/2000/svg");
|
|
|
|
| 3297 |
clone.setAttribute("width", W);
|
| 3298 |
clone.setAttribute("height", H);
|
| 3299 |
clone.removeAttribute("style");
|
|
|
|
| 3305 |
const canvas=document.createElement("canvas");
|
| 3306 |
canvas.width=W*scale; canvas.height=H*scale;
|
| 3307 |
const ctx=canvas.getContext("2d");
|
|
|
|
| 3308 |
ctx.fillStyle="#ffffff";
|
| 3309 |
ctx.fillRect(0,0,canvas.width,canvas.height);
|
| 3310 |
ctx.scale(scale,scale);
|
|
|
|
| 3329 |
return html
|
| 3330 |
|
| 3331 |
|
|
|
|
|
|
|
| 3332 |
def draw_interactions_rdkit_classic(
|
| 3333 |
lig_mol,
|
| 3334 |
receptor_pdb: str,
|
|
|
|
| 3338 |
size: tuple = (650, 620),
|
| 3339 |
max_residues: int = 10,
|
| 3340 |
) -> bytes:
|
| 3341 |
+
"""RDKit highlight-circle style 2D interaction diagram. Returns SVG bytes."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3342 |
from rdkit import Chem, RDLogger
|
| 3343 |
from rdkit.Chem import Draw, rdDepictor, AllChem
|
| 3344 |
|
| 3345 |
RDLogger.DisableLog("rdApp.*")
|
| 3346 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3347 |
_C_HB = (0.35, 0.61, 0.84, 0.45)
|
| 3348 |
_C_HP = (0.17, 0.55, 0.34, 0.45)
|
| 3349 |
_C_OT = (0.80, 0.37, 0.54, 0.45)
|
|
|
|
| 3363 |
except Exception:
|
| 3364 |
return None
|
| 3365 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3366 |
W, H = size
|
| 3367 |
mol2d = _parse_robust(smiles)
|
| 3368 |
if mol2d is None:
|
|
|
|
| 3385 |
idx3d_to_2d[i3d] = i2d
|
| 3386 |
except: pass
|
| 3387 |
|
|
|
|
| 3388 |
try:
|
|
|
|
| 3389 |
raw = _detect_all_interactions(lig_mol, receptor_pdb, cutoff=cutoff)
|
| 3390 |
except:
|
| 3391 |
raw = []
|
| 3392 |
|
|
|
|
| 3393 |
for ix in raw:
|
| 3394 |
ix["lig_atom_idx"] = idx3d_to_2d.get(ix.get("lig_atom_idx", 0), 0)
|
| 3395 |
|
|
|
|
| 3396 |
pm = {t: i for i, t in enumerate(_ITYPE_PRIORITY)}
|
| 3397 |
deduped = _deduplicate_interactions(raw)
|
| 3398 |
deduped.sort(key=lambda x: (pm.get(x["itype"], 99), x["distance"]))
|
|
|
|
| 3405 |
RDLogger.EnableLog("rdApp.error")
|
| 3406 |
return d2d.GetDrawingText().encode()
|
| 3407 |
|
|
|
|
| 3408 |
lig_ext = Chem.RWMol(mol2d)
|
| 3409 |
pts, clrs = [], {}
|
| 3410 |
|
|
|
|
| 3412 |
itype = ix["itype"]
|
| 3413 |
ai = ix.get("lig_atom_idx", 0)
|
| 3414 |
if ai >= n2d: ai = 0
|
|
|
|
|
|
|
| 3415 |
|
|
|
|
| 3416 |
if itype in ("hbond", "hbond_to_halogen"):
|
| 3417 |
color = _C_HB
|
| 3418 |
elif itype == "hydrophobic":
|
|
|
|
| 3421 |
color = _C_OT
|
| 3422 |
|
| 3423 |
rn = ix["resname"]; ri = ix["resid"]; ch = ix.get("chain","")
|
| 3424 |
+
_NO_NUM = HEME_RESNAMES | METAL_RESNAMES
|
| 3425 |
+
lbl = rn.upper() if rn.upper() in _NO_NUM else f"{rn}{ri}{ch}"
|
| 3426 |
|
| 3427 |
res_atom = Chem.Atom(0)
|
| 3428 |
res_atom.SetProp("atomLabel", lbl)
|