Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files16 unmodified lines1718192021222320212223242530262728293031323334353637383940413536374243449 unmodified lines5455565354555657585960616263646566676862636471727374657677787980818283848586878889909192939495666768697071727374991001017576777879801051061078182838485863 unmodified lines909192117118119120121939412295124125126127128129130131132133969798991001011371021031041411421431441451461471481051061071521531541551081091101111121131141151161611171181191201211221681231241254 unmodified lines1301311321791801811331341351361371861871881381391401911921931941411421431 unmodified line1451461472022032042052062072082092101481492132142152162172182192202211501511521531541551561571581591601616 unmodified lines1681691702341712361721732392402412421741751761772461781792491801812522532542551821831841851861871881892611901912642652661921932681941951961972732742752762771981992002013 unmodified lines2052062072872082092104 unmodified lines2152162172982182192204 unmodified lines22522622730922822923031323123223331723423523623723832323924024124224332924424524616 unmodified lines2632642653523532662672682693572703592712722731 unmodified line27527627736736836937037127827937328028128214 unmodified lines2972982993943953963973003013023033044033054053063073083094094103103113123133144154163153163173183193203213223233243253264194203273283293303314233323333343353364283373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663674444454463683693703714483723734504513743753763773783793803814553824574583833843854603863873883893903913921 unmodified line3943953964693973983994004014024034764044054064074084814824094104114124854864874884134144154167 unmodified lines4244254265025035045055065075085094274284294305124314325154334344354364374385214394404415245255265274424435305314444454464474484494505374514524534544555435444564574584594604614625514634644654 unmodified lines47047147256256347347447556647647756957047847948057348148248319 unmodified lines50350450559950660160260360460560650750850951051161161261361451251351418 unmodified lines5335345356395365375388 unmodified lines5475485496545505515525 unmodified lines5585595606666676686695615625635645655665675687 unmodified lines5765775786835795805817 unmodified lines5895905916975925935947017027037045955965971 unmodified line5996006017127137147156026036047197206056066076086096107266116127297307317326136146156166176187387397407416196206216 unmodified lines62862963075463163263363463563613 unmodified lines6506516527746537766546556566576586596606616626636646656666676686 unmodified lines67567667779467867968013 unmodified lines6946956966976986997007018188197027037042 unmodified lines7077087098288298308318328338347107117127137147157167177187197207215 unmodified lines7277287298468478488497307317327337348557357367377388598608618628638648658667397407417427437447458728738748757467477488787498807507517527537547558877568897577587597607617628967637648999009019029039049057657669077677687697707719127727737747759177769197777789227797807817829279289299307837847857867877887899379389399409419429439449459469479489499509519529539547907917927937947957969567977989587998008019618028038046 unmodified lines811812813974975976977978979980981982814815816984817818987819989990991992993994995996997998999100010011002820821822823824825826827828829830831100410051006100710081009101010111012101383283310161017101810191020834835836102310241025102683783883984015 unmodified lines856857858104885986010508611052862863864865866105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114286786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590616 unmodified linesfrom rdkit.Chem import AllChem
# ----------------------------# Constants and directories# ----------------------------
SUPPORTED_PROTEIN_EXTS = {".pdb", ".pdbqt"}SUPPORTED_LIGAND_EXTS = {".sdf", ".mol", ".mol2", ".pdb", ".pdbqt"}
APP_TMP_ROOT = Path("/tmp/docking_streamlit_app")UPLOAD_ROOT = APP_TMP_ROOT / "uploads"EXPORT_ROOT = APP_TMP_ROOT / "exports"
UPLOAD_ROOT.mkdir(parents=True, exist_ok=True)EXPORT_ROOT.mkdir(parents=True, exist_ok=True)
STANDARD_AA = { "ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE", "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL", "ASH", "GLH", "HID", "HIE", "HIP", "LYN", "CYM", "CYX", "ARN", "GLM"}
AA_RENAMES = { "MSE": "MET", "HSD": "HIS", "HSE": "HIS", "HSP": "HIS",}
# ----------------------------# Data classes# ----------------------------
@dataclassclass AtomRecord:9 unmodified lines line: str
# ----------------------------# Command helpers# ----------------------------
def ensure_command(cmd: str) -> bool: return shutil.which(cmd) is not None
def run_cmd(cmd: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess: return subprocess.run( cmd, cwd=cwd, text=True, capture_output=True, check=False, ) return subprocess.run(cmd, cwd=cwd, text=True, capture_output=True, check=False)
# ----------------------------# Session helpers# ----------------------------
def init_state() -> None: if "session_id" not in st.session_state: st.session_state["session_id"] = uuid.uuid4().hex[:12]
if "run_outputs" not in st.session_state: st.session_state["run_outputs"] = None
if "saved_protein_path" not in st.session_state: st.session_state["saved_protein_path"] = None
if "saved_ligand_path" not in st.session_state: st.session_state["saved_ligand_path"] = None
if "saved_protein_name" not in st.session_state: st.session_state["saved_protein_name"] = None
if "saved_ligand_name" not in st.session_state: st.session_state["saved_ligand_name"] = None
if "upload_notice" not in st.session_state: st.session_state["upload_notice"] = None st.session_state.setdefault("session_id", uuid.uuid4().hex[:12]) st.session_state.setdefault("run_outputs", None) st.session_state.setdefault("saved_protein_path", None) st.session_state.setdefault("saved_ligand_path", None) st.session_state.setdefault("saved_protein_name", None) st.session_state.setdefault("saved_ligand_name", None)
def get_session_dir() -> Path: session_dir = UPLOAD_ROOT / st.session_state["session_id"] session_dir.mkdir(parents=True, exist_ok=True) return session_dir p = UPLOAD_ROOT / st.session_state["session_id"] p.mkdir(parents=True, exist_ok=True) return p
def get_export_dir() -> Path: export_dir = EXPORT_ROOT / st.session_state["session_id"] export_dir.mkdir(parents=True, exist_ok=True) return export_dir p = EXPORT_ROOT / st.session_state["session_id"] p.mkdir(parents=True, exist_ok=True) return p
def safe_filename(name: str) -> str:3 unmodified lines
def reset_all() -> None: session_dir = get_session_dir() export_dir = get_export_dir()
shutil.rmtree(session_dir, ignore_errors=True) shutil.rmtree(export_dir, ignore_errors=True) shutil.rmtree(get_session_dir(), ignore_errors=True) shutil.rmtree(get_export_dir(), ignore_errors=True)
for key in [ "protein_uploader", "ligand_uploader", "smiles_text", "residue_selection_text", "run_outputs", "saved_protein_path", "saved_ligand_path", "saved_protein_name", "saved_ligand_name", "upload_notice", "protein_uploader", "ligand_uploader", "smiles_text", "residue_selection_text", "run_outputs", "saved_protein_path", "saved_ligand_path", "saved_protein_name", "saved_ligand_name" ]: if key in st.session_state: del st.session_state[key]
st.rerun()
# ----------------------------# Upload helpers# ----------------------------
def file_size_mb(path: Path) -> float: return round(path.stat().st_size / (1024 * 1024), 3)
def save_uploaded_file(uploaded_file, out_path: Path) -> Path: out_path.parent.mkdir(parents=True, exist_ok=True) uploaded_file.seek(0) with open(out_path, "wb") as fout: fout.write(uploaded_file.getbuffer()) fout.flush() os.fsync(fout.fileno()) with open(out_path, "wb") as f: f.write(uploaded_file.getbuffer()) f.flush() os.fsync(f.fileno()) return out_path
def persist_uploads(protein_upload, ligand_upload) -> None: session_dir = get_session_dir()
if protein_upload is not None: protein_name = safe_filename(protein_upload.name) protein_path = session_dir / f"protein_{protein_name}" save_uploaded_file(protein_upload, protein_path) st.session_state["saved_protein_path"] = str(protein_path) st.session_state["saved_protein_name"] = protein_upload.name
if ligand_upload is not None: ligand_name = safe_filename(ligand_upload.name) ligand_path = session_dir / f"ligand_{ligand_name}"4 unmodified lines
def get_saved_protein_path() -> Optional[Path]: p = st.session_state.get("saved_protein_path") if p and Path(p).exists(): return Path(p) return None return Path(p) if p and Path(p).exists() else None
def get_saved_ligand_path() -> Optional[Path]: p = st.session_state.get("saved_ligand_path") if p and Path(p).exists(): return Path(p) return None return Path(p) if p and Path(p).exists() else None
# ----------------------------# PDB/PDBQT parsing helpers# ----------------------------
def parse_pdb_like_atoms(file_path: Path) -> List[AtomRecord]: atoms: List[AtomRecord] = [] with open(file_path, "r", errors="ignore") as f:1 unmodified line if not (line.startswith("ATOM") or line.startswith("HETATM")): continue try: record = line[0:6].strip() serial = int(line[6:11].strip() or 0) atom_name = line[12:16].strip() res_name = line[17:20].strip() chain_id = line[21].strip() or "A" res_seq = int(line[22:26].strip() or 0) x = float(line[30:38].strip()) y = float(line[38:46].strip()) z = float(line[46:54].strip()) atoms.append( AtomRecord( record=record, serial=serial, atom_name=atom_name, res_name=res_name, chain_id=chain_id, res_seq=res_seq, x=x, y=y, z=z, record=line[0:6].strip(), serial=int(line[6:11].strip() or 0), atom_name=line[12:16].strip(), res_name=line[17:20].strip(), chain_id=line[21].strip() or "A", res_seq=int(line[22:26].strip() or 0), x=float(line[30:38].strip()), y=float(line[38:46].strip()), z=float(line[46:54].strip()), line=line, ) )6 unmodified lines selections: List[Tuple[str, int, Optional[str]]] = [] if not selection_text.strip(): return selections
blocks = [b.strip() for b in selection_text.split(";") if b.strip()]
for block in blocks: if ":" not in block: raise ValueError( f"Invalid residue block '{block}'. Use formats like A:45, A:LYS45, or A:45-50." )
raise ValueError(f"Invalid residue block '{block}'. Use A:45, A:LYS45, or A:45-50.") chain, spec = block.split(":", 1) chain = chain.strip() spec = spec.strip()
if not chain: raise ValueError(f"Missing chain in block '{block}'.")
items = [x.strip() for x in spec.split(",") if x.strip()] for item in items: m_range_num = re.fullmatch(r"(\d+)\s*-\s*(\d+)", item) if m_range_num: start = int(m_range_num.group(1)) end = int(m_range_num.group(2)) m_range = re.fullmatch(r"(\d+)\s*-\s*(\d+)", item) if m_range: start, end = int(m_range.group(1)), int(m_range.group(2)) if end < start: raise ValueError(f"Invalid range '{item}' in block '{block}'.") for rnum in range(start, end + 1): selections.append((chain, rnum, None)) continue
m_named = re.fullmatch(r"([A-Za-z]{3})(\d+)", item) if m_named: res_name = m_named.group(1).upper() res_num = int(m_named.group(2)) selections.append((chain, res_num, res_name)) selections.append((chain, int(m_named.group(2)), m_named.group(1).upper())) continue
m_num = re.fullmatch(r"(\d+)", item) if m_num: selections.append((chain, int(m_num.group(1)), None)) continue
raise ValueError( f"Could not parse residue item '{item}'. Use A:45, A:45-50, or A:LYS45." )
raise ValueError(f"Could not parse residue item '{item}'.") return selections
3 unmodified lines) -> List[AtomRecord]: atoms = parse_pdb_like_atoms(protein_file) matched_atoms: List[AtomRecord] = []
for atom in atoms: for chain_id, res_num, res_name in selections: if atom.chain_id != chain_id:4 unmodified lines continue matched_atoms.append(atom) break
return matched_atoms
4 unmodified lines) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]: if not atoms: raise ValueError("No atoms were found for box calculation.")
xs = [a.x for a in atoms] ys = [a.y for a in atoms] zs = [a.z for a in atoms]
xmin, xmax = min(xs), max(xs) ymin, ymax = min(ys), max(ys) zmin, zmax = min(zs), max(zs)
center = ( round((xmin + xmax) / 2.0, 3), round((ymin + ymax) / 2.0, 3), round((zmin + zmax) / 2.0, 3), )
size = ( round(max((xmax - xmin) + 2 * padding, min_size), 3), round(max((ymax - ymin) + 2 * padding, min_size), 3), round(max((zmax - zmin) + 2 * padding, min_size), 3), )
return center, size
16 unmodified lines) -> Tuple[Tuple[float, float, float], Tuple[float, float, float], pd.DataFrame]: selections = parse_residue_selection(residue_selection_text) if not selections: raise ValueError("Provide at least one residue selection, e.g. A:LYS45,ASP46 or A:45-50.")
raise ValueError("Provide at least one residue selection.") selected_atoms = get_atoms_for_selected_residues(protein_file, selections) if not selected_atoms: raise ValueError("None of the specified residues were found in the uploaded protein file.")
center, size = compute_box_from_atoms(selected_atoms, padding=padding, min_size=min_size)
matched_rows = [] seen = set() for atom in selected_atoms:1 unmodified line if key not in seen: seen.add(key) matched_rows.append( { "chain": atom.chain_id, "residue_number": atom.res_seq, "residue_name": atom.res_name, } {"chain": atom.chain_id, "residue_number": atom.res_seq, "residue_name": atom.res_name} )
matched_df = pd.DataFrame(sorted(matched_rows, key=lambda x: (x["chain"], x["residue_number"]))) return center, size, matched_df
14 unmodified lines fout.write("END\n")
# ----------------------------# Receptor preparation# ----------------------------
def infer_element_from_atom_name(atom_name: str) -> str: atom_name = (atom_name or "").strip() letters = "".join(ch for ch in atom_name if ch.isalpha()) if not letters: return ""
letters = letters.upper() two_letter_elements = { two_letter = { "CL", "BR", "NA", "MG", "AL", "SI", "CA", "CR", "MN", "FE", "CO", "NI", "CU", "ZN", "SE", "CD", "HG" }
if len(letters) >= 2 and letters[:2] in two_letter_elements: if len(letters) >= 2 and letters[:2] in two_letter: return letters[:2].capitalize() return letters[0].capitalize()
def clean_receptor_pdb_for_meeko(infile: Path, outfile: Path) -> None: kept = 0def strict_clean_receptor_pdb(infile: Path, outfile: Path) -> Dict[str, int]: stats = { "kept_atoms": 0, "dropped_non_atom": 0, "dropped_hydrogen": 0, "dropped_water": 0, "dropped_altloc": 0, "dropped_nonstandard": 0, "renamed_residue": 0, }
with open(infile, "r", errors="ignore") as fin, open(outfile, "w") as fout: for line in fin: if not line.startswith("ATOM"): for raw_line in fin: if not raw_line.startswith("ATOM"): stats["dropped_non_atom"] += 1 continue
line = line.rstrip("\n") line = raw_line.rstrip("\n") if len(line) < 80: line = line.ljust(80)
atom_name = line[12:16].strip() res_name = line[17:20].strip().upper() altloc = line[16].strip() res_name = line[17:20].strip().upper() element = line[76:78].strip()
if res_name in {"HOH", "WAT"}: stats["dropped_water"] += 1 continue
if altloc not in {"", "A"}: stats["dropped_altloc"] += 1 continue
if not element: element = infer_element_from_atom_name(atom_name) if element.upper() == "H" or atom_name.upper().startswith("H"): stats["dropped_hydrogen"] += 1 continue
if res_name in AA_RENAMES: res_name = AA_RENAMES[res_name] line = line[:17] + f"{res_name:>3}" + line[20:] stats["renamed_residue"] += 1
if res_name not in STANDARD_AA: stats["dropped_nonstandard"] += 1 continue
if not element: stats["dropped_nonstandard"] += 1 continue
newline = line[:76] + f"{element:>2}" + line[78:] fout.write(newline + "\n") kept += 1 line = line[:76] + f"{element:>2}" + line[78:] fout.write(line + "\n") stats["kept_atoms"] += 1
fout.write("END\n") fout.write("TER\nEND\n")
if kept == 0: raise ValueError("No valid ATOM records remained after receptor cleaning.") if stats["kept_atoms"] == 0: raise ValueError( "No valid standard protein atoms remained after strict receptor cleaning." ) return stats
def validate_receptor_pdbqt(pdbqt_path: Path) -> None: bad_tags = ("ROOT", "BRANCH", "ENDBRANCH", "TORSDOF") text = pdbqt_path.read_text(errors="ignore") found = [tag for tag in bad_tags if tag in text] if found: bad_tags = [tag for tag in ("ROOT", "BRANCH", "ENDBRANCH", "TORSDOF") if tag in text] if bad_tags: raise RuntimeError( f"Invalid receptor PDBQT: found ligand-only tag(s): {', '.join(found)}" f"Invalid receptor PDBQT: found ligand-only tag(s): {', '.join(bad_tags)}" ) if "ATOM" not in text and "HETATM" not in text: raise RuntimeError("Receptor PDBQT appears empty or invalid.")
def prepare_receptor_pdbqt(1 unmodified line protein_file: Path, center: Tuple[float, float, float], size: Tuple[float, float, float],) -> Tuple[Path, Path]:) -> Tuple[Path, Path, Dict[str, int]]: protein_suffix = protein_file.suffix.lower()
if protein_suffix == ".pdbqt": pdbqt_path = work_dir / "receptor_input.pdbqt" shutil.copy2(protein_file, pdbqt_path) validate_receptor_pdbqt(pdbqt_path) return pdbqt_path, protein_file return pdbqt_path, protein_file, {"kept_atoms": -1}
if protein_suffix != ".pdb": raise ValueError("Protein must be PDB or PDBQT.")
cleaned_pdb = work_dir / "receptor_cleaned.pdb" clean_receptor_pdb_for_meeko(protein_file, cleaned_pdb) cleaned_pdb = work_dir / "receptor_cleaned_strict.pdb" clean_stats = strict_clean_receptor_pdb(protein_file, cleaned_pdb)
if not ensure_command("mk_prepare_receptor.py"): raise RuntimeError( "mk_prepare_receptor.py is required for receptor preparation but was not found. " "Please fix the Docker image instead of using Open Babel as a receptor fallback." ) raise RuntimeError("mk_prepare_receptor.py is required for receptor preparation but was not found.")
out_base = work_dir / "receptor" cmd = [7 unmodified lines ] result = run_cmd(cmd, cwd=str(work_dir))
candidates = [ work_dir / "receptor.pdbqt", work_dir / "receptor_rigid.pdbqt", work_dir / "receptor_rigid.pdbqt".replace(".pdbqt", "") if False else work_dir / "dummy" ]
real_candidates = [work_dir / "receptor.pdbqt", work_dir / "receptor_rigid.pdbqt"] pdbqt_path = next((p for p in real_candidates if p.exists()), None) candidates = [work_dir / "receptor.pdbqt", work_dir / "receptor_rigid.pdbqt"] pdbqt_path = next((p for p in candidates if p.exists()), None)
if result.returncode != 0 or pdbqt_path is None: generated = [p.name for p in work_dir.glob("*.pdbqt")] raise RuntimeError( "Receptor preparation with mk_prepare_receptor.py failed.\n" f"Generated PDBQT files: {generated}\n" f"Cleaning stats: {json.dumps(clean_stats)}\n" f"STDOUT:\n{result.stdout}\n" f"STDERR:\n{result.stderr}" )
validate_receptor_pdbqt(pdbqt_path) return pdbqt_path, cleaned_pdb return pdbqt_path, cleaned_pdb, clean_stats
# ----------------------------# Ligand preparation# ----------------------------
def validate_ligand_pdbqt(pdbqt_path: Path) -> None: text = pdbqt_path.read_text(errors="ignore") if "ROOT" not in text and "ATOM" not in text and "HETATM" not in text: raise RuntimeError("Ligand PDBQT appears to be invalid or empty.") if "ATOM" not in text and "HETATM" not in text: raise RuntimeError("Ligand PDBQT appears empty or invalid.")
def ligand_mol_from_input(ligand_file: Optional[Path], smiles_text: str) -> Tuple[Chem.Mol, str]: if ligand_file is None and not smiles_text.strip(): raise ValueError("Provide either a ligand file or a SMILES string.")
if smiles_text.strip(): mol = Chem.MolFromSmiles(smiles_text.strip()) if mol is None: raise ValueError("Invalid SMILES string.") mol = Chem.AddHs(mol) status = AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) if status != 0: if AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) != 0: raise ValueError("RDKit could not build a 3D conformer from the SMILES string.") AllChem.UFFOptimizeMolecule(mol, maxIters=500) return mol, "smiles"
assert ligand_file is not None suffix = ligand_file.suffix.lower()
if suffix == ".sdf": suppl = Chem.SDMolSupplier(str(ligand_file), removeHs=False) mol = next((m for m in suppl if m is not None), None)4 unmodified lines elif suffix == ".pdb": mol = Chem.MolFromPDBFile(str(ligand_file), removeHs=False) else: raise ValueError("Ligand file type not supported for RDKit preparation. Use SDF, MOL, MOL2, PDB, or SMILES.")
raise ValueError("Ligand file type not supported for RDKit preparation.") if mol is None: raise ValueError("Could not parse the ligand file.")
if mol.GetNumConformers() == 0: mol = Chem.AddHs(mol) status = AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) if status != 0: if AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) != 0: raise ValueError("Could not generate a 3D conformer for the ligand.") AllChem.UFFOptimizeMolecule(mol, maxIters=500)
return mol, suffix.lstrip(".")
19 unmodified lines
out_pdbqt = work_dir / "ligand.pdbqt" result = run_cmd(["obabel", str(sdf_path), "-O", str(out_pdbqt), "-xh"], cwd=str(work_dir))
if result.returncode != 0 or not out_pdbqt.exists(): raise RuntimeError( "Ligand preparation failed.\n" f"STDOUT:\n{result.stdout}\n" f"STDERR:\n{result.stderr}" )
raise RuntimeError(f"Ligand preparation failed.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}") validate_ligand_pdbqt(out_pdbqt) return out_pdbqt
# ----------------------------# Docking result parsing# ----------------------------
VINA_TABLE_RE = re.compile(r"^\s*(\d+)\s+(-?\d+\.\d+)\s+([0-9.]+)\s+([0-9.]+)\s*$")
18 unmodified lines lines = [] in_first_model = False saw_model = False
with open(pdbqt_path, "r", errors="ignore") as f: for line in f: if line.startswith("MODEL"):8 unmodified lines lines.append(line) else: lines.append(line)
with open(out_path, "w") as out: out.writelines(lines) out.write("END\n")5 unmodified lines for line in f: if line.startswith(("ATOM", "HETATM")): try: x = float(line[30:38].strip()) y = float(line[38:46].strip()) z = float(line[46:54].strip()) coords.append((x, y, z)) coords.append(( float(line[30:38].strip()), float(line[38:46].strip()), float(line[46:54].strip()), )) except Exception: continue return coords7 unmodified lines receptor_atoms = parse_pdb_like_atoms(receptor_source) ligand_xyz = parse_xyz_from_pdbqt(ligand_pose_pdbqt) residues: Dict[Tuple[str, int, str], Dict[str, float]] = {}
for atom in receptor_atoms: atom_xyz = (atom.x, atom.y, atom.z) dmin = min((distance(atom_xyz, lig) for lig in ligand_xyz), default=999.0)7 unmodified lines "residue_name": atom.res_name, "min_distance_A": round(dmin, 3), }
return pd.DataFrame(sorted(residues.values(), key=lambda x: x["min_distance_A"]))
# ----------------------------# Export helpers# ----------------------------
def make_zip(zip_path: Path, files: List[Path]) -> None: with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for fp in files:1 unmodified line zf.write(fp, arcname=fp.name)
# ----------------------------# Validation helpers# ----------------------------
def validate_extension(name: str, allowed: set[str], label: str) -> None: suffix = Path(name).suffix.lower() if suffix not in allowed: allowed_text = ", ".join(sorted(allowed)) raise ValueError(f"{label} must be one of: {allowed_text}") raise ValueError(f"{label} must be one of: {', '.join(sorted(allowed))}")
def validate_input_file_content(file_path: Path, label: str) -> None: if not file_path.exists(): raise ValueError(f"{label} file was not saved correctly.")
if file_path.stat().st_size == 0: raise ValueError(f"{label} file is empty.")
suffix = file_path.suffix.lower()
if suffix in {".pdb", ".pdbqt"}: if file_path.suffix.lower() in {".pdb", ".pdbqt"}: text = file_path.read_text(errors="ignore") if "ATOM" not in text and "HETATM" not in text: raise ValueError(f"{label} file does not appear to contain valid atomic records.")
# ----------------------------# Docking engine# ----------------------------
def run_docking( protein_file: Path, ligand_file: Optional[Path],6 unmodified lines with tempfile.TemporaryDirectory(prefix="dockapp_job_") as tmpdir: work_dir = Path(tmpdir)
receptor_pdbqt, receptor_source = prepare_receptor_pdbqt(work_dir, protein_file, center, size) receptor_pdbqt, receptor_source, clean_stats = prepare_receptor_pdbqt( work_dir, protein_file, center, size ) ligand_pdbqt = prepare_ligand_pdbqt(work_dir, ligand_file, smiles_text)
docked_pdbqt = work_dir / "docked_out.pdbqt"13 unmodified lines "--num_modes", str(num_modes), "--out", str(docked_pdbqt), ]
result = run_cmd(cmd, cwd=str(work_dir)) log_path.write_text((result.stdout or "") + "\n" + (result.stderr or "")) log_path.write_text( f"Receptor cleaning stats: {json.dumps(clean_stats)}\n\n" + (result.stdout or "") + "\n" + (result.stderr or "") )
if result.returncode != 0 or not docked_pdbqt.exists(): raise RuntimeError( "Docking failed.\n" f"Command: {' '.join(cmd)}\n" f"Receptor cleaning stats: {json.dumps(clean_stats)}\n" f"STDOUT:\n{result.stdout}\n" f"STDERR:\n{result.stderr}" )6 unmodified lines residues_csv = work_dir / "active_site_residues.csv" scores_csv = work_dir / "docking_scores.csv" summary_json = work_dir / "summary.json"
residues_df.to_csv(residues_csv, index=False) scores_df.to_csv(scores_csv, index=False)
13 unmodified lines "grid_size": {"x": size[0], "y": size[1], "z": size[2]}, "best_affinity_kcal_per_mol": best_aff, "n_active_site_residues": int(len(residues_df)), "receptor_cleaning_stats": clean_stats, } summary_json.write_text(json.dumps(payload, indent=2))
export_dir = get_export_dir() export_dir.mkdir(parents=True, exist_ok=True)
out_map = { "docked_pdbqt": export_dir / "docked_out.pdbqt", "best_pose_pdbqt": export_dir / "best_pose_model1.pdbqt",2 unmodified lines "summary_json": export_dir / "summary.json", "log_txt": export_dir / "docking.log", }
shutil.copy2(docked_pdbqt, out_map["docked_pdbqt"]) shutil.copy2(best_pose, out_map["best_pose_pdbqt"]) shutil.copy2(scores_csv, out_map["scores_csv"]) shutil.copy2(residues_csv, out_map["residues_csv"]) shutil.copy2(summary_json, out_map["summary_json"]) shutil.copy2(log_path, out_map["log_txt"]) for src_key, src_path in [ ("docked_pdbqt", docked_pdbqt), ("best_pose_pdbqt", best_pose), ("scores_csv", scores_csv), ("residues_csv", residues_csv), ("summary_json", summary_json), ("log_txt", log_path), ]: shutil.copy2(src_path, out_map[src_key])
if residue_pdb.exists(): out_map["active_site_pdb"] = export_dir / "active_site_residues.pdb"5 unmodified lines return out_map
# ----------------------------# UI# ----------------------------
def main() -> None: st.set_page_config(page_title="Protein-Ligand Docking Tool", layout="wide") init_state()
st.title("Protein-Ligand Docking Tool") st.caption("Upload a protein and ligand, save them to the session, then run blind, residue-based, or manual docking.") st.caption("Save uploads first, then run docking with stricter receptor cleaning.")
with st.sidebar: st.header("Run settings") exhaustiveness = st.slider("Exhaustiveness", min_value=4, max_value=64, value=8, step=4) num_modes = st.slider("Number of poses", min_value=1, max_value=20, value=9, step=1)
st.markdown("**Required tools**") st.markdown("- vina") st.markdown("- obabel") st.markdown("- mk_prepare_receptor.py")
exhaustiveness = st.slider("Exhaustiveness", 4, 64, 8, 4) num_modes = st.slider("Number of poses", 1, 20, 9, 1) if st.button("Clear all inputs and results"): reset_all()
missing_cmds = [cmd for cmd in ["vina", "obabel", "mk_prepare_receptor.py"] if not ensure_command(cmd)] if missing_cmds: st.warning( "Missing container tools: " + ", ".join(missing_cmds) + ". " "Docking will fail until the Docker image is fixed." ) st.warning("Missing container tools: " + ", ".join(missing_cmds))
st.subheader("Step 1: Upload input files")
col1, col2 = st.columns(2)
with col1: protein_upload = st.file_uploader( "Upload protein structure (PDB or PDBQT)", type=["pdb", "pdbqt"], accept_multiple_files=False, key="protein_uploader", help="Upload a receptor file in PDB or PDBQT format.", )
with col2: ligand_upload = st.file_uploader( "Upload ligand (SDF, MOL, MOL2, PDB, or PDBQT)", type=["sdf", "mol", "mol2", "pdb", "pdbqt"], accept_multiple_files=False, key="ligand_uploader", help="Upload a ligand file in SDF, MOL, MOL2, PDB, or PDBQT format.", )
smiles_text = st.text_area( "Or paste ligand SMILES", placeholder="CC(=O)Oc1ccccc1C(=O)O", key="smiles_text", )
save_uploads_clicked = st.button("Save uploaded files", type="secondary") smiles_text = st.text_area("Or paste ligand SMILES", key="smiles_text")
if save_uploads_clicked: if st.button("Save uploaded files"): try: if protein_upload is None: raise ValueError("Upload a protein file before saving.") validate_extension(protein_upload.name, SUPPORTED_PROTEIN_EXTS, "Protein file")
if ligand_upload is None and not smiles_text.strip(): raise ValueError("Upload a ligand file or provide a SMILES string before saving.") if ligand_upload is not None: validate_extension(ligand_upload.name, SUPPORTED_LIGAND_EXTS, "Ligand file")
persist_uploads(protein_upload, ligand_upload)
protein_path = get_saved_protein_path() ligand_path = get_saved_ligand_path()
if protein_path is not None: validate_input_file_content(protein_path, "Protein") if ligand_path is not None: validate_input_file_content(ligand_path, "Ligand")
st.session_state["upload_notice"] = "Files saved successfully for this session." st.success(st.session_state["upload_notice"])
st.success("Files saved successfully for this session.") except Exception as e: st.error(str(e))
protein_path = get_saved_protein_path() ligand_path = get_saved_ligand_path()
st.subheader("Saved session files")
left, right = st.columns(2) with left: if protein_path is not None: st.success( f"Protein ready: {st.session_state.get('saved_protein_name', protein_path.name)} " f"({file_size_mb(protein_path)} MB)" ) else: st.info("No saved protein yet.")
with right: if ligand_path is not None: st.success( f"Ligand ready: {st.session_state.get('saved_ligand_name', ligand_path.name)} " f"({file_size_mb(ligand_path)} MB)" ) c1, c2 = st.columns(2) with c1: st.info(f"Protein: {protein_path.name if protein_path else 'Not saved yet'}") with c2: if ligand_path: st.info(f"Ligand: {ligand_path.name}") elif smiles_text.strip(): st.success("SMILES input ready.") st.info("Ligand: SMILES input") else: st.info("No saved ligand yet.") st.info("Ligand: Not saved yet")
st.subheader("Step 2: Docking mode and box definition")
docking_mode = st.radio( "Choose docking mode", ["Residue-based docking", "Blind docking", "Manual box coordinates"],6 unmodified lines size_x = size_y = size_z = 20.0
if docking_mode == "Residue-based docking": st.code( "Examples:\nA:LYS45,ASP46,GLU47\nA:45,46,47\nA:45-50\nA:LYS45;B:TYR120", language="text", ) residue_selection_text = st.text_area( "Residues and chains", placeholder="A:LYS45,ASP46,GLU47", key="residue_selection_text", ) st.code("Examples:\nA:LYS45,ASP46\nA:45-50\nA:LYS45;B:TYR120") residue_selection_text = st.text_area("Residues and chains", key="residue_selection_text") padding = st.number_input("Padding around selected residues (Å)", min_value=2.0, value=8.0, step=1.0)
elif docking_mode == "Blind docking": padding = st.number_input("Blind docking padding (Å)", min_value=2.0, value=8.0, step=1.0)
else: c1, c2, c3 = st.columns(3) center_x = c1.number_input("Center X", value=0.0, format="%.3f") center_y = c2.number_input("Center Y", value=0.0, format="%.3f") center_z = c3.number_input("Center Z", value=0.0, format="%.3f")
s1, s2, s3 = st.columns(3) size_x = s1.number_input("Size X", value=20.0, min_value=5.0, format="%.3f") size_y = s2.number_input("Size Y", value=20.0, min_value=5.0, format="%.3f") size_z = s3.number_input("Size Z", value=20.0, min_value=5.0, format="%.3f")
run_disabled = bool(missing_cmds) or (protein_path is None) or ((ligand_path is None) and (not smiles_text.strip())) run_clicked = st.button("Run docking", type="primary", disabled=run_disabled)
if run_clicked: a, b, c = st.columns(3) center_x = a.number_input("Center X", value=0.0, format="%.3f") center_y = b.number_input("Center Y", value=0.0, format="%.3f") center_z = c.number_input("Center Z", value=0.0, format="%.3f") d, e, f = st.columns(3) size_x = d.number_input("Size X", value=20.0, min_value=5.0, format="%.3f") size_y = e.number_input("Size Y", value=20.0, min_value=5.0, format="%.3f") size_z = f.number_input("Size Z", value=20.0, min_value=5.0, format="%.3f")
run_disabled = bool(missing_cmds) or protein_path is None or (ligand_path is None and not smiles_text.strip()) if st.button("Run docking", type="primary", disabled=run_disabled): try: if protein_path is None: raise ValueError("Save a protein file before running docking.")
if ligand_path is None and not smiles_text.strip(): raise ValueError("Save a ligand file or provide a SMILES string before running docking.")
validate_input_file_content(protein_path, "Protein") if ligand_path is not None: validate_input_file_content(ligand_path, "Ligand")
residue_match_df = None if docking_mode == "Blind docking": center, size = compute_blind_docking_box( protein_path, padding=padding, min_size=20.0, ) center, size = compute_blind_docking_box(protein_path, padding=padding, min_size=20.0) elif docking_mode == "Residue-based docking": center, size, residue_match_df = compute_residue_based_box( protein_path, residue_selection_text=residue_selection_text, padding=padding, min_size=18.0, protein_path, residue_selection_text=residue_selection_text, padding=padding, min_size=18.0 ) else: center = (center_x, center_y, center_z)15 unmodified lines "center": center, "size": size, "mode": docking_mode, "matched_residues": residue_match_df.to_dict(orient="records") if residue_match_df is not None else None, "matched_residues": None if residue_match_df is None else residue_match_df.to_dict(orient="records"), }
st.success("Docking completed successfully.")
except Exception as e: st.error(str(e))
outputs_raw = st.session_state.get("run_outputs") if outputs_raw: try: outputs = {k: Path(v) for k, v in outputs_raw["files"].items()} center = tuple(outputs_raw["center"]) size = tuple(outputs_raw["size"]) docking_mode_used = outputs_raw["mode"] matched_residues = outputs_raw.get("matched_residues")
scores_df = pd.read_csv(outputs["scores_csv"]) residues_df = pd.read_csv(outputs["residues_csv"]) summary = json.loads(outputs["summary_json"].read_text())
st.subheader("Computed docking box") b1, b2, b3 = st.columns(3) with b1: st.metric("Center X", center[0]) st.metric("Size X", size[0]) with b2: st.metric("Center Y", center[1]) st.metric("Size Y", size[1]) with b3: st.metric("Center Z", center[2]) st.metric("Size Z", size[2])
st.info(f"Docking mode used: {docking_mode_used}")
if docking_mode_used == "Residue-based docking" and matched_residues: st.subheader("Matched residues used to define the box") st.dataframe(pd.DataFrame(matched_residues), use_container_width=True)
m1, m2 = st.columns(2) with m1: st.metric("Best binding affinity (kcal/mol)", summary.get("best_affinity_kcal_per_mol")) with m2: st.metric("Predicted active-site residues", summary.get("n_active_site_residues"))
st.subheader("Docking score table") st.dataframe(scores_df, use_container_width=True)
st.subheader("Predicted active-site residues") if residues_df.empty: st.warning("No residues were found within 4.5 Å of the best docked pose.") else: st.dataframe(residues_df, use_container_width=True)
st.subheader("Downloads") with open(outputs["scores_csv"], "rb") as f: st.download_button( "Download docking scores CSV", f.read(), file_name="docking_scores.csv", mime="text/csv", ) with open(outputs["residues_csv"], "rb") as f: st.download_button( "Download active-site residues CSV", f.read(), file_name="active_site_residues.csv", mime="text/csv", ) with open(outputs["best_pose_pdbqt"], "rb") as f: st.download_button( "Download best docked pose PDBQT", f.read(), file_name="best_pose_model1.pdbqt", ) if "active_site_pdb" in outputs and outputs["active_site_pdb"].exists(): with open(outputs["active_site_pdb"], "rb") as f: st.download_button( "Download active-site residues structure PDB", f.read(), file_name="active_site_residues.pdb", ) with open(outputs["zip"], "rb") as f: st.download_button( "Download complete results ZIP", f.read(), file_name="docking_results_bundle.zip", mime="application/zip", )
with st.expander("Show docking log"): st.code(outputs["log_txt"].read_text(errors="ignore"), language="text")
except Exception as e: st.error(f"Could not display stored results: {e}") outputs = {k: Path(v) for k, v in outputs_raw["files"].items()} center = tuple(outputs_raw["center"]) size = tuple(outputs_raw["size"]) scores_df = pd.read_csv(outputs["scores_csv"]) residues_df = pd.read_csv(outputs["residues_csv"]) summary = json.loads(outputs["summary_json"].read_text())
st.subheader("Computed docking box") x1, x2, x3 = st.columns(3) x1.metric("Center X", center[0]) x1.metric("Size X", size[0]) x2.metric("Center Y", center[1]) x2.metric("Size Y", size[1]) x3.metric("Center Z", center[2]) x3.metric("Size Z", size[2])
st.metric("Best binding affinity (kcal/mol)", summary.get("best_affinity_kcal_per_mol")) st.json(summary.get("receptor_cleaning_stats", {}))
st.subheader("Docking score table") st.dataframe(scores_df, use_container_width=True)
st.subheader("Predicted active-site residues") if residues_df.empty: st.warning("No residues were found within 4.5 Å of the best docked pose.") else: st.dataframe(residues_df, use_container_width=True)
with open(outputs["zip"], "rb") as f: st.download_button( "Download complete results ZIP", f.read(), file_name="docking_results_bundle.zip", mime="application/zip", ) with st.expander("Show docking log"): st.code(outputs["log_txt"].read_text(errors="ignore"), language="text")
if __name__ == "__main__":qsar_core_streamlit.py+209-448