#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import os import re import shutil import subprocess import tempfile import uuid import zipfile from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Optional, Tuple import pandas as pd import streamlit as st from rdkit import Chem from rdkit.Chem import AllChem SUPPORTED_PROTEIN_EXTS = {".pdb", ".pdbqt"} SUPPORTED_LIGAND_EXTS = {".sdf", ".mol", ".mol2", ".pdb", ".pdbqt"} APP_TMP_ROOT = Path("/tmp/batch_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", } @dataclass class AtomRecord: record: str serial: int atom_name: str res_name: str chain_id: str res_seq: int x: float y: float z: float line: str def ensure_command(cmd: str) -> bool: return shutil.which(cmd) is not None def resolve_command(*names: str) -> Optional[str]: """Return the first available executable from a list of candidate names.""" for name in names: resolved = shutil.which(name) if resolved: return resolved return None def count_atomic_records(file_path: Path) -> int: """Count PDB/PDBQT ATOM and HETATM records without loading the whole file.""" count = 0 with open(file_path, "r", errors="ignore") as handle: for line in handle: if line.startswith(("ATOM", "HETATM")): count += 1 return count def write_command_log(log_path: Path, command: List[str], result) -> None: log_path.parent.mkdir(parents=True, exist_ok=True) log_path.write_text( "COMMAND:\n" + " ".join(command) + "\n\nRETURN CODE:\n" + str(result.returncode) + "\n\nSTDOUT:\n" + _as_text(result.stdout) + "\n\nSTDERR:\n" + _as_text(result.stderr), encoding="utf-8", ) def _as_text(value): """Convert subprocess output safely to text. This prevents Streamlit/write_text errors such as: data must be str, not bytes. """ if value is None: return "" if isinstance(value, bytes): return value.decode("utf-8", errors="replace") return str(value) def run_cmd(cmd: List[str], cwd: Optional[str] = None, timeout: int = 600): try: result = subprocess.run( cmd, cwd=cwd, text=True, capture_output=True, check=False, timeout=timeout, ) result.stdout = _as_text(result.stdout) result.stderr = _as_text(result.stderr) return result except subprocess.TimeoutExpired as e: return subprocess.CompletedProcess( cmd, returncode=124, stdout=_as_text(e.stdout), stderr=f"TIMEOUT after {timeout} seconds\n" + _as_text(e.stderr) ) def init_state(): st.session_state.setdefault("session_id", uuid.uuid4().hex[:12]) st.session_state.setdefault("run_outputs", None) def get_session_dir() -> Path: p = UPLOAD_ROOT / st.session_state["session_id"] p.mkdir(parents=True, exist_ok=True) return p def get_export_dir() -> Path: p = EXPORT_ROOT / st.session_state["session_id"] p.mkdir(parents=True, exist_ok=True) return p def safe_filename(name: str) -> str: name = Path(str(name)).name name = re.sub(r"[^A-Za-z0-9._-]+", "_", name) return name or "file" def reset_all(): shutil.rmtree(get_session_dir(), ignore_errors=True) shutil.rmtree(get_export_dir(), ignore_errors=True) st.session_state.clear() st.rerun() 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 f: f.write(uploaded_file.getbuffer()) f.flush() os.fsync(f.fileno()) return out_path def validate_extension(name: str, allowed: set, label: str): suffix = Path(name).suffix.lower() if suffix not in allowed: raise ValueError(f"{label} must be one of: {', '.join(sorted(allowed))}") def validate_input_file_content(file_path: Path, label: str): 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.") 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 contain valid atomic records.") def parse_pdb_like_atoms(file_path: Path) -> List[AtomRecord]: atoms = [] with open(file_path, "r", errors="ignore") as f: for line in f: if not line.startswith(("ATOM", "HETATM")): continue try: atoms.append( AtomRecord( 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, ) ) except Exception: continue return atoms def parse_residue_selection(selection_text: str) -> List[Tuple[str, int, Optional[str]]]: selections = [] 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 A:45, A:LYS45, or A:45-50.") chain, spec = block.split(":", 1) chain = chain.strip() items = [x.strip() for x in spec.split(",") if x.strip()] for item in items: 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)) 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: 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}'.") return selections def get_atoms_for_selected_residues(protein_file: Path, selections): atoms = parse_pdb_like_atoms(protein_file) matched = [] for atom in atoms: for chain_id, res_num, res_name in selections: if atom.chain_id != chain_id: continue if atom.res_seq != res_num: continue if res_name is not None and atom.res_name.upper() != res_name.upper(): continue matched.append(atom) break return matched def compute_box_from_atoms(atoms, padding=8.0, min_size=18.0): 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] center = ( round((min(xs) + max(xs)) / 2.0, 3), round((min(ys) + max(ys)) / 2.0, 3), round((min(zs) + max(zs)) / 2.0, 3), ) size = ( round(max((max(xs) - min(xs)) + 2 * padding, min_size), 3), round(max((max(ys) - min(ys)) + 2 * padding, min_size), 3), round(max((max(zs) - min(zs)) + 2 * padding, min_size), 3), ) return center, size def limit_box_size(size, max_size=25.0): """Limit Vina grid dimensions to avoid very large search spaces. Vina becomes slow and may timeout when the search-space volume is above 27000 Angstrom^3. A 25 x 25 x 25 box gives 15625 Angstrom^3. """ return tuple(round(min(float(x), max_size), 3) for x in size) def box_volume(size): return round(float(size[0]) * float(size[1]) * float(size[2]), 3) def compute_blind_docking_box(protein_file: Path, padding=8.0, min_size=20.0): atoms = parse_pdb_like_atoms(protein_file) if not atoms: raise ValueError("No protein atoms were found.") return compute_box_from_atoms(atoms, padding, min_size) def compute_residue_based_box(protein_file: Path, residue_selection_text: str, padding=8.0, min_size=18.0): selections = parse_residue_selection(residue_selection_text) if not selections: 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 selected residues were found.") return compute_box_from_atoms(selected_atoms, padding, min_size) def infer_element_from_atom_name(atom_name: str, is_standard_residue_atom: bool = False) -> str: """Infer an element symbol from a PDB atom name when the element column is blank. ``is_standard_residue_atom`` must be True only when the atom belongs to a standard amino acid ATOM record (never a HETATM/ligand/ion record). This matters because several two-letter ion/element symbols are also valid protein atom names, most importantly "CA": in a HETATM record "CA" means the calcium ion, but in an ATOM record for any of the 20 standard amino acids "CA" is always the backbone alpha-carbon and must resolve to carbon. Silently treating every alpha-carbon as calcium corrupts the element of the single most common atom in the entire structure and breaks downstream residue-template matching (e.g. in Meeko) for virtually every residue. """ atom_name = (atom_name or "").strip() letters = "".join(ch for ch in atom_name if ch.isalpha()).upper() if not letters: return "" if is_standard_residue_atom: # Protein ATOM records never legitimately contain a bound metal ion # under a standard atom name, so two-letter ion symbols are not # applicable here regardless of collision. Standard backbone/side # chain atom names always start with the correct single-letter # element (C, N, O, S), so plain single-letter typing is correct. return letters[0].capitalize() two_letter = {"CL", "BR", "NA", "MG", "AL", "SI", "CA", "CR", "MN", "FE", "CO", "NI", "CU", "ZN", "SE"} if len(letters) >= 2 and letters[:2] in two_letter: return letters[:2].capitalize() return letters[0].capitalize() def 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, "dropped_bad_element": 0, } with open(infile, "r", errors="ignore") as fin, open(outfile, "w") as fout: for raw_line in fin: if not raw_line.startswith("ATOM"): stats["dropped_non_atom"] += 1 continue line = raw_line.rstrip("\n") if len(line) < 80: line = line.ljust(80) atom_name = line[12:16].strip() 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 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: element = infer_element_from_atom_name(atom_name, is_standard_residue_atom=True) if not element: stats["dropped_bad_element"] += 1 continue if element.upper() == "H" or atom_name.upper().startswith("H"): stats["dropped_hydrogen"] += 1 continue line = line[:76] + f"{element:>2}" + line[78:] fout.write(line + "\n") stats["kept_atoms"] += 1 fout.write("TER\nEND\n") if stats["kept_atoms"] == 0: raise ValueError("No valid protein atoms remained after cleaning.") return stats def validate_receptor_pdbqt(pdbqt_path: Path, minimum_atoms: int = 20) -> Dict[str, int]: if not pdbqt_path.exists(): raise RuntimeError(f"Receptor PDBQT was not created: {pdbqt_path}") size_bytes = pdbqt_path.stat().st_size if size_bytes < 200: raise RuntimeError( f"Receptor PDBQT is too small ({size_bytes} bytes), indicating failed preparation." ) text = pdbqt_path.read_text(errors="ignore") bad_tags = [tag for tag in ("ROOT", "BRANCH", "ENDBRANCH", "TORSDOF") if tag in text] if bad_tags: raise RuntimeError( "Invalid receptor PDBQT: ligand-only torsion tags were found: " + ", ".join(bad_tags) ) atom_count = sum( 1 for line in text.splitlines() if line.startswith(("ATOM", "HETATM")) ) if atom_count < minimum_atoms: raise RuntimeError( f"Receptor PDBQT contains only {atom_count} atomic records; " f"at least {minimum_atoms} were expected." ) return {"atom_count": atom_count, "size_bytes": size_bytes} def validate_ligand_pdbqt(pdbqt_path: Path): text = pdbqt_path.read_text(errors="ignore") if "ATOM" not in text and "HETATM" not in text: raise RuntimeError("Ligand PDBQT appears empty.") def pdb_residue_key(line: str) -> Tuple[str, int, str]: """Return chain, residue number and insertion code for a PDB ATOM line.""" chain_id = line[21:22].strip() or "A" try: residue_number = int(line[22:26].strip()) except Exception as exc: raise ValueError(f"Invalid PDB residue number in line: {line.rstrip()}") from exc insertion_code = line[26:27].strip() return chain_id, residue_number, insertion_code def find_interrupted_pdb_residues(pdb_path: Path) -> List[str]: """Find residues whose ATOM records occur in multiple separated blocks. Meeko requires all atoms belonging to a residue to be contiguous in the PDB. Some hydrogen-addition converters write all heavy atoms first and append hydrogens later, which makes almost every residue appear interrupted. """ completed_blocks = set() interrupted = set() current_key = None with open(pdb_path, "r", errors="ignore") as handle: for line in handle: if not line.startswith("ATOM"): continue key = pdb_residue_key(line) if key != current_key: if key in completed_blocks: interrupted.add(key) if current_key is not None: completed_blocks.add(current_key) current_key = key return [ f"{chain}:{number}{icode}" for chain, number, icode in sorted(interrupted) ] def rewrite_pdb_with_contiguous_residues(input_pdb: Path, output_pdb: Path) -> Dict[str, object]: """Group ATOM records by residue while preserving first-seen residue order.""" header_lines = [] residue_order = [] residue_lines = {} with open(input_pdb, "r", errors="ignore") as handle: for line in handle: if line.startswith("ATOM"): key = pdb_residue_key(line) if key not in residue_lines: residue_order.append(key) residue_lines[key] = [] residue_lines[key].append(line.rstrip("\n")) elif line.startswith(("CRYST1", "REMARK")): header_lines.append(line.rstrip("\n")) if not residue_order: raise RuntimeError("No ATOM records were available for residue-order repair.") with open(output_pdb, "w") as handle: for line in header_lines: handle.write(line + "\n") previous_chain = None atom_count = 0 for key in residue_order: chain_id = key[0] if previous_chain is not None and chain_id != previous_chain: handle.write("TER\n") for atom_line in residue_lines[key]: handle.write(atom_line + "\n") atom_count += 1 previous_chain = chain_id handle.write("TER\nEND\n") remaining = find_interrupted_pdb_residues(output_pdb) if remaining: raise RuntimeError( "Residue-order repair failed; interrupted residues remain: " + ", ".join(remaining[:20]) ) return { "strategy": "group_atoms_by_residue", "residue_count": len(residue_order), "atom_count": atom_count, } def protonate_receptor_pdb( cleaned_pdb: Path, protonated_pdb: Path, work_dir: Path, timeout: int = 600, ) -> Tuple[Path, Dict[str, object]]: """Add receptor hydrogens with Open Babel when available. Meeko receptor preparation is most reliable when hydrogen atoms are present. If Open Babel protonation fails, the cleaned PDB is retained and Meeko is still attempted, with the complete failure log preserved for diagnosis. """ obabel = resolve_command("obabel") if not obabel: return cleaned_pdb, { "strategy": "cleaned_pdb_without_added_hydrogens", "reason": "Open Babel executable was not found", } command = [ obabel, str(cleaned_pdb), "-O", str(protonated_pdb), "-h", "-p", "7.4", ] result = run_cmd(command, cwd=str(work_dir), timeout=timeout) write_command_log(work_dir / "receptor_protonation.log", command, result) if result.returncode != 0 or not protonated_pdb.exists(): return cleaned_pdb, { "strategy": "cleaned_pdb_after_protonation_failure", "returncode": result.returncode, "stderr": _as_text(result.stderr)[-2000:], } atom_count = count_atomic_records(protonated_pdb) if atom_count < 20: return cleaned_pdb, { "strategy": "cleaned_pdb_after_invalid_protonated_output", "protonated_atom_count": atom_count, } return protonated_pdb, { "strategy": "openbabel_pH_7.4", "protonated_atom_count": atom_count, } def get_meeko_runtime_capabilities( meeko_executable: str, work_dir: Path, timeout: int = 60, ) -> Dict[str, object]: """Inspect the installed Meeko CLI instead of assuming release-specific flags. Hugging Face Docker images may contain a Meeko executable from Conda while the Python package is later replaced by pip. Querying ``--help`` at runtime prevents unsupported options such as ``--delete_bad_res`` from being passed to an older entry point. """ help_result = run_cmd([meeko_executable, "--help"], cwd=str(work_dir), timeout=timeout) help_text = (_as_text(help_result.stdout) + "\n" + _as_text(help_result.stderr)).strip() (work_dir / "meeko_receptor_cli_help.txt").write_text( help_text or "No help text was returned.", encoding="utf-8", ) version_text = "unknown" try: from importlib.metadata import version as package_version version_text = package_version("meeko") except Exception: pass def supported(option: str) -> bool: return option in help_text # Prefer long options because short options have changed meaning between # Meeko releases. if supported("--delete_bad_res"): bad_res_option = "--delete_bad_res" elif supported("--allow_bad_res"): bad_res_option = "--allow_bad_res" elif re.search(r"(^|[\s,])-a([\s,]|$)", help_text): bad_res_option = "-a" else: bad_res_option = None capabilities = { "python_package_version": version_text, "executable": meeko_executable, "help_returncode": help_result.returncode, "supports_read_pdb": supported("--read_pdb"), "supports_read_with_prody": supported("--read_with_prody"), "supports_write_pdbqt": supported("--write_pdbqt"), "supports_output_basename": supported("--output_basename"), "supports_default_altloc": supported("--default_altloc"), "supports_box_center": supported("--box_center"), "supports_box_size": supported("--box_size"), "bad_res_option": bad_res_option, "help_file": str(work_dir / "meeko_receptor_cli_help.txt"), } (work_dir / "meeko_runtime_capabilities.json").write_text( json.dumps(capabilities, indent=2), encoding="utf-8", ) return capabilities def build_meeko_receptor_command( meeko: str, receptor_input_pdb: Path, output_basename: Path, requested_pdbqt: Path, center, size, capabilities: Dict[str, object], tolerant: bool, ) -> List[str]: """Build a receptor command using only options reported by ``--help``.""" command = [meeko] if capabilities.get("supports_read_pdb"): command.extend(["--read_pdb", str(receptor_input_pdb)]) elif capabilities.get("supports_read_with_prody"): command.extend(["--read_with_prody", str(receptor_input_pdb)]) else: # ``-i`` is the stable input form shown in the Meeko release README. command.extend(["-i", str(receptor_input_pdb)]) if capabilities.get("supports_write_pdbqt"): command.extend(["--write_pdbqt", str(requested_pdbqt)]) else: # Older and some packaged CLIs use an output basename plus the ``-p`` # switch. Meeko then writes basename.pdbqt or basename_rigid.pdbqt. command.extend(["-o", str(output_basename), "-p"]) if capabilities.get("supports_default_altloc"): command.extend(["--default_altloc", "A"]) if capabilities.get("supports_box_center"): command.extend([ "--box_center", str(center[0]), str(center[1]), str(center[2]), ]) if capabilities.get("supports_box_size"): command.extend([ "--box_size", str(size[0]), str(size[1]), str(size[2]), ]) if tolerant and capabilities.get("bad_res_option"): command.append(str(capabilities["bad_res_option"])) return command def collect_meeko_pdbqt_candidates( work_dir: Path, output_basename: Path, requested_pdbqt: Path, ) -> List[Path]: """Return possible rigid receptor outputs across Meeko CLI generations.""" candidates = [ requested_pdbqt, output_basename.with_suffix(".pdbqt"), output_basename.parent / f"{output_basename.name}_rigid.pdbqt", output_basename.parent / f"{output_basename.name}_flex.pdbqt", ] candidates.extend(sorted(work_dir.glob(f"{output_basename.name}*.pdbqt"))) unique = [] seen = set() for candidate in candidates: key = str(candidate.resolve()) if candidate.exists() else str(candidate) if key not in seen: seen.add(key) unique.append(candidate) return unique def prepare_receptor_once(work_dir: Path, protein_file: Path, center, size, timeout=600): """Prepare one rigid receptor PDBQT with runtime-compatible Meeko syntax. The function first performs a strict preparation. If that fails and the installed CLI advertises a bad-residue tolerance option, one controlled retry is made with that exact supported option. Open Babel is not used to protonate or create the receptor PDBQT because it can reorder residue atoms or generate empty or ligand-style receptor files. """ work_dir.mkdir(parents=True, exist_ok=True) suffix = protein_file.suffix.lower() if suffix == ".pdbqt": receptor_pdbqt = work_dir / "prepared_receptor.pdbqt" receptor_source = work_dir / "receptor_source_input.pdbqt" shutil.copy2(protein_file, receptor_pdbqt) shutil.copy2(protein_file, receptor_source) validation = validate_receptor_pdbqt(receptor_pdbqt) return receptor_pdbqt, receptor_source, { "strategy": "validated_input_pdbqt", "validation": validation, } cleaned_pdb = work_dir / "receptor_cleaned.pdb" clean_stats = strict_clean_receptor_pdb(protein_file, cleaned_pdb) cleaned_atom_count = count_atomic_records(cleaned_pdb) if cleaned_atom_count < 20: raise RuntimeError( f"Only {cleaned_atom_count} receptor atoms remained after cleaning. " "Check chain selection, residue names, alternate locations and PDB formatting." ) # Do not protonate the receptor with Open Babel before Meeko. Open Babel # commonly appends hydrogen records after the heavy-atom block, making the # atoms of each residue non-contiguous. Meeko then raises # ``ValueError: interrupted residues in PDB`` for most or all residues. # Meeko can add missing hydrogens internally during residue-template matching. interrupted_before = find_interrupted_pdb_residues(cleaned_pdb) if interrupted_before: reordered_pdb = work_dir / "receptor_cleaned_contiguous.pdb" residue_order_info = rewrite_pdb_with_contiguous_residues( cleaned_pdb, reordered_pdb ) receptor_input_pdb = reordered_pdb else: receptor_input_pdb = cleaned_pdb residue_order_info = { "strategy": "original_cleaned_order_already_contiguous", "interrupted_residues_before": 0, } interrupted_after = find_interrupted_pdb_residues(receptor_input_pdb) if interrupted_after: raise RuntimeError( "The receptor still contains interrupted residues after repair: " + ", ".join(interrupted_after[:20]) ) protonation_info = { "strategy": "meeko_internal_missing_hydrogen_completion", "openbabel_receptor_protonation_used": False, "reason": ( "Open Babel receptor protonation was disabled because it can reorder " "PDB atom records and cause Meeko interrupted-residue errors." ), "residue_order_validation": residue_order_info, } meeko = resolve_command("mk_prepare_receptor.py", "mk_prepare_receptor") if not meeko: raise RuntimeError( "Meeko receptor preparation executable was not found. Confirm that " "mk_prepare_receptor.py or mk_prepare_receptor is installed and on PATH." ) capabilities = get_meeko_runtime_capabilities(meeko, work_dir) receptor_pdbqt = work_dir / "prepared_receptor.pdbqt" # Always perform a strict attempt. Add a tolerant attempt only when the # executable itself reports a supported option. attempts = [{"name": "strict", "tolerant": False}] if capabilities.get("bad_res_option"): attempts.append({ "name": f"tolerant_{str(capabilities['bad_res_option']).lstrip('-')}", "tolerant": True, }) attempt_reports = [] for attempt_index, attempt in enumerate(attempts, start=1): attempt_base = work_dir / f"prepared_receptor_attempt_{attempt_index}" attempt_requested = work_dir / f"prepared_receptor_attempt_{attempt_index}.pdbqt" # Remove outputs belonging to this attempt so stale files can never be # mistaken for successful receptor preparation. for old_file in work_dir.glob(f"{attempt_base.name}*.pdbqt"): old_file.unlink(missing_ok=True) attempt_requested.unlink(missing_ok=True) receptor_pdbqt.unlink(missing_ok=True) command = build_meeko_receptor_command( meeko=meeko, receptor_input_pdb=receptor_input_pdb, output_basename=attempt_base, requested_pdbqt=attempt_requested, center=center, size=size, capabilities=capabilities, tolerant=bool(attempt["tolerant"]), ) result = run_cmd(command, cwd=str(work_dir), timeout=timeout) log_path = work_dir / f"meeko_receptor_attempt_{attempt_index}_{attempt['name']}.log" write_command_log(log_path, command, result) candidate_reports = [] valid_output = None if result.returncode == 0: for candidate in collect_meeko_pdbqt_candidates( work_dir=work_dir, output_basename=attempt_base, requested_pdbqt=attempt_requested, ): candidate_report = { "path": str(candidate), "exists": candidate.exists(), "size_bytes": candidate.stat().st_size if candidate.exists() else 0, } if candidate.exists(): try: validation = validate_receptor_pdbqt(candidate) candidate_report["validation"] = validation # Prefer the rigid output when both rigid and flexible # receptor files were produced. if valid_output is None or "_rigid" in candidate.name: valid_output = candidate except Exception as exc: candidate_report["validation_error"] = str(exc) candidate_reports.append(candidate_report) report = { "attempt": attempt["name"], "command": command, "returncode": result.returncode, "stdout_tail": _as_text(result.stdout)[-3000:], "stderr_tail": _as_text(result.stderr)[-5000:], "candidates": candidate_reports, } if result.returncode == 0 and valid_output is not None: shutil.copy2(valid_output, receptor_pdbqt) validation = validate_receptor_pdbqt(receptor_pdbqt) report["selected_output"] = str(valid_output) report["validation"] = validation attempt_reports.append(report) return receptor_pdbqt, cleaned_pdb, { "strategy": "meeko_runtime_compatible_cli", "meeko_runtime": capabilities, "successful_attempt": attempt["name"], "cleaning_stats": clean_stats, "cleaned_atom_count": cleaned_atom_count, "protonation": protonation_info, "validation": validation, "attempts": attempt_reports, } attempt_reports.append(report) diagnostic_json = work_dir / "receptor_preparation_failed.json" diagnostic_json.write_text( json.dumps( { "protein_file": str(protein_file), "cleaning_stats": clean_stats, "cleaned_atom_count": cleaned_atom_count, "protonation": protonation_info, "meeko_runtime": capabilities, "attempts": attempt_reports, }, indent=2, ), encoding="utf-8", ) first_error = attempt_reports[0].get("stderr_tail", "") if attempt_reports else "" last_error = attempt_reports[-1].get("stderr_tail", "") if attempt_reports else "" raise RuntimeError( "Meeko receptor preparation failed, so docking was stopped before Vina. " f"The cleaned receptor contained {cleaned_atom_count} atoms. " f"Detected Meeko Python package version: {capabilities.get('python_package_version')}. " f"Detected bad-residue option: {capabilities.get('bad_res_option') or 'none'}. " f"Diagnostic files were saved in {work_dir}.\n\n" f"Strict-attempt error:\n{first_error}\n\n" f"Last-attempt error:\n{last_error}" ) def ligand_mol_from_input(ligand_file: Path): 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) elif suffix == ".mol": mol = Chem.MolFromMolFile(str(ligand_file), removeHs=False) elif suffix == ".mol2": mol = Chem.MolFromMol2File(str(ligand_file), removeHs=False) elif suffix == ".pdb": mol = Chem.MolFromPDBFile(str(ligand_file), removeHs=False) else: raise ValueError("Ligand file type not supported for RDKit preparation.") if mol is None: raise ValueError("Could not parse ligand file.") if mol.GetNumConformers() == 0: mol = Chem.AddHs(mol) if AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) != 0: raise ValueError("Could not generate 3D conformer.") AllChem.UFFOptimizeMolecule(mol, maxIters=300) return mol def prepare_ligand_pdbqt(work_dir: Path, ligand_file: Path, timeout=300): """Prepare ligand PDBQT using Open Babel directly. This is faster and more reliable for COCONUT/PubChem PDB ligands because many downloaded ligand PDB files contain HETATM records but no CONECT/bond table. RDKit may fail or guess wrong bonds in such files. Open Babel handles these ligand formats better for docking preparation. """ if ligand_file.suffix.lower() == ".pdbqt": dst = work_dir / "ligand.pdbqt" shutil.copy2(ligand_file, dst) validate_ligand_pdbqt(dst) return dst if not ensure_command("obabel"): raise RuntimeError("obabel is required for ligand preparation.") out_pdbqt = work_dir / "ligand.pdbqt" # Direct conversion is preferred for SDF/MOL/MOL2/PDB files. # -h adds hydrogens; --partialcharge gasteiger assigns charges for Vina. cmd = [ "obabel", str(ligand_file), "-O", str(out_pdbqt), "-h", "--partialcharge", "gasteiger", ] result = run_cmd(cmd, cwd=str(work_dir), timeout=timeout) if result.returncode != 0 or not out_pdbqt.exists(): raise RuntimeError( "Ligand preparation failed with Open Babel.\n" f"Command: {' '.join(cmd)}\n" f"STDOUT:\n{_as_text(result.stdout)}\n" f"STDERR:\n{_as_text(result.stderr)}" ) validate_ligand_pdbqt(out_pdbqt) return out_pdbqt def prepare_smiles_ligand_pdbqt(work_dir: Path, smiles: str, ligand_name: str, timeout=300): mol = Chem.MolFromSmiles(smiles.strip()) if mol is None: raise ValueError("Invalid SMILES.") mol = Chem.AddHs(mol) if AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) != 0: raise ValueError("RDKit could not build 3D conformer.") AllChem.UFFOptimizeMolecule(mol, maxIters=300) sdf_path = work_dir / f"{safe_filename(ligand_name)}.sdf" writer = Chem.SDWriter(str(sdf_path)) writer.write(mol) writer.close() out_pdbqt = work_dir / "ligand.pdbqt" result = run_cmd( ["obabel", str(sdf_path), "-O", str(out_pdbqt), "-xh"], cwd=str(work_dir), timeout=timeout, ) if result.returncode != 0 or not out_pdbqt.exists(): raise RuntimeError( "SMILES ligand preparation failed.\n" f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" ) validate_ligand_pdbqt(out_pdbqt) return out_pdbqt VINA_TABLE_RE = re.compile(r"^\s*(\d+)\s+(-?\d+\.\d+)\s+([0-9.]+)\s+([0-9.]+)\s*$") def parse_vina_stdout(stdout_text: str) -> pd.DataFrame: rows = [] for line in stdout_text.splitlines(): m = VINA_TABLE_RE.match(line.strip()) if m: rows.append( { "mode": int(m.group(1)), "affinity_kcal_per_mol": float(m.group(2)), "rmsd_lb": float(m.group(3)), "rmsd_ub": float(m.group(4)), } ) return pd.DataFrame(rows) def split_first_model_pdbqt(pdbqt_path: Path, out_path: Path): 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"): saw_model = True parts = line.split() in_first_model = len(parts) > 1 and parts[1] == "1" continue if line.startswith("ENDMDL") and in_first_model: break if saw_model: if in_first_model: lines.append(line) else: lines.append(line) with open(out_path, "w") as out: out.writelines(lines) out.write("END\n") def convert_structure_to_pdb(input_path: Path, output_path: Path, timeout=300): if input_path.suffix.lower() == ".pdb": if input_path.resolve() != output_path.resolve(): shutil.copy2(input_path, output_path) return output_path if not ensure_command("obabel"): raise RuntimeError("obabel is required to convert structure to PDB.") result = run_cmd( ["obabel", str(input_path), "-O", str(output_path)], timeout=timeout, ) if result.returncode != 0 or not output_path.exists(): raise RuntimeError( f"Failed to convert {input_path.name} to PDB.\n" f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" ) return output_path def combine_protein_and_ligand_pdb(receptor_pdb: Path, ligand_pdb: Path, complex_pdb: Path): """ Combine receptor and docked ligand into one PDB complex. This revised version preserves ligand atom names and element columns as much as possible so LigPlot/LigPlus can keep its normal default coloring. The ligand is still written as HETATM with residue name LIG and chain Z. """ serial = 1 def safe_int(field, default=1): try: return int(str(field).strip()) except Exception: return default def safe_float(field, default=0.0): try: return float(str(field).strip()) except Exception: return default def normalize_atom_line(line, record, atom_serial, force_resname=None, force_chain=None, force_resseq=None): line = line.rstrip("\n") if len(line) < 80: line = line.ljust(80) atom_name = line[12:16] altloc = " " res_name = force_resname if force_resname is not None else (line[17:20].strip() or "UNK") chain_id = force_chain if force_chain is not None else (line[21].strip() or "A") res_seq = force_resseq if force_resseq is not None else safe_int(line[22:26], 1) x = safe_float(line[30:38]) y = safe_float(line[38:46]) z = safe_float(line[46:54]) occ = safe_float(line[54:60], 1.00) bfac = safe_float(line[60:66], 0.00) element = line[76:78].strip() if not element: # record is "ATOM" for the receptor and "HETATM" for the docked # ligand; only the receptor side is guaranteed to be a standard # amino acid, so only there can "CA" safely be forced to carbon. element = infer_element_from_atom_name( atom_name.strip(), is_standard_residue_atom=(record == "ATOM") ) or "C" charge = line[78:80].strip() return ( f"{record:<6}" f"{atom_serial:5d} " f"{atom_name:<4}" f"{altloc}" f"{res_name[:3].upper():>3} " f"{chain_id[:1]}" f"{res_seq:4d}" f" " f"{x:8.3f}{y:8.3f}{z:8.3f}" f"{occ:6.2f}{bfac:6.2f}" f" " f"{element:>2}{charge:>2}" ) with open(complex_pdb, "w") as out: with open(receptor_pdb, "r", errors="ignore") as fin: for line in fin: if not line.startswith("ATOM"): continue out.write( normalize_atom_line( line=line, record="ATOM", atom_serial=serial, ) + "\n" ) serial += 1 out.write("TER\n") ligand_atom_count = 0 with open(ligand_pdb, "r", errors="ignore") as fin: for line in fin: if not line.startswith(("ATOM", "HETATM")): continue out.write( normalize_atom_line( line=line, record="HETATM", atom_serial=serial, force_resname="LIG", force_chain="Z", force_resseq=1, ) + "\n" ) serial += 1 ligand_atom_count += 1 if ligand_atom_count == 0: raise RuntimeError("No ligand atoms were found while generating the complex PDB.") out.write("END\n") def make_zip(zip_path: Path, folder: Path): with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for fp in folder.rglob("*"): if fp.is_file(): zf.write(fp, arcname=fp.relative_to(folder)) def dock_single_ligand( ligand_source, ligand_kind, receptor_pdbqt: Path, receptor_source: Path, batch_dir: Path, center, size, exhaustiveness, num_modes, vina_timeout, prep_timeout, cpu_threads, ): ligand_name = ligand_source.name if ligand_kind == "file" else ligand_source["name"] ligand_dir = batch_dir / safe_filename(Path(ligand_name).stem) ligand_dir.mkdir(parents=True, exist_ok=True) try: if ligand_kind == "file": ligand_pdbqt = prepare_ligand_pdbqt(ligand_dir, ligand_source, timeout=prep_timeout) else: ligand_pdbqt = prepare_smiles_ligand_pdbqt( ligand_dir, ligand_source["smiles"], ligand_source["name"], timeout=prep_timeout, ) docked_pdbqt = ligand_dir / "docked_out.pdbqt" cmd = [ "vina", "--receptor", str(receptor_pdbqt), "--ligand", str(ligand_pdbqt), "--center_x", str(center[0]), "--center_y", str(center[1]), "--center_z", str(center[2]), "--size_x", str(size[0]), "--size_y", str(size[1]), "--size_z", str(size[2]), "--exhaustiveness", str(exhaustiveness), "--num_modes", str(num_modes), "--cpu", str(cpu_threads), "--out", str(docked_pdbqt), ] result = run_cmd(cmd, cwd=str(ligand_dir), timeout=vina_timeout) (ligand_dir / "vina_stdout.txt").write_text(result.stdout or "") (ligand_dir / "vina_stderr.txt").write_text(result.stderr or "") if result.returncode != 0 or not docked_pdbqt.exists(): return { "ligand": ligand_name, "status": "FAILED", "best_affinity_kcal_per_mol": "", "best_mode": "", "rmsd_lb": "", "rmsd_ub": "", "num_modes_generated": "", "error": f"Vina failed or timed out. STDERR: {result.stderr[-500:]}", "complex_pdb": "", "scores_csv": "", } scores_df = parse_vina_stdout((result.stdout or "") + "\n" + (result.stderr or "")) if scores_df.empty: return { "ligand": ligand_name, "status": "FAILED", "best_affinity_kcal_per_mol": "", "best_mode": "", "rmsd_lb": "", "rmsd_ub": "", "num_modes_generated": "", "error": "Docking completed but score table was not parsed.", "complex_pdb": "", "scores_csv": "", } scores_csv = ligand_dir / "docking_scores.csv" scores_df.to_csv(scores_csv, index=False) best_pose_pdbqt = ligand_dir / "best_pose_model1.pdbqt" best_pose_pdb = ligand_dir / "best_ligand_pose.pdb" receptor_pdb = ligand_dir / "receptor_for_complex.pdb" complex_pdb = ligand_dir / "best_protein_ligand_complex.pdb" split_first_model_pdbqt(docked_pdbqt, best_pose_pdbqt) convert_structure_to_pdb(receptor_source, receptor_pdb, timeout=prep_timeout) convert_structure_to_pdb(best_pose_pdbqt, best_pose_pdb, timeout=prep_timeout) combine_protein_and_ligand_pdb(receptor_pdb, best_pose_pdb, complex_pdb) best_row = scores_df.iloc[0] summary = { "ligand": ligand_name, "status": "SUCCESS", "best_mode": int(best_row["mode"]), "best_affinity_kcal_per_mol": float(best_row["affinity_kcal_per_mol"]), "rmsd_lb": float(best_row["rmsd_lb"]), "rmsd_ub": float(best_row["rmsd_ub"]), "num_modes_generated": int(len(scores_df)), "grid_center": {"x": center[0], "y": center[1], "z": center[2]}, "grid_size": {"x": size[0], "y": size[1], "z": size[2]}, "complex_pdb": str(complex_pdb), "scores_csv": str(scores_csv), } (ligand_dir / "summary.json").write_text(json.dumps(summary, indent=2)) return { "ligand": ligand_name, "status": "SUCCESS", "best_mode": int(best_row["mode"]), "best_affinity_kcal_per_mol": float(best_row["affinity_kcal_per_mol"]), "rmsd_lb": float(best_row["rmsd_lb"]), "rmsd_ub": float(best_row["rmsd_ub"]), "num_modes_generated": int(len(scores_df)), "error": "", "complex_pdb": str(complex_pdb), "scores_csv": str(scores_csv), } except Exception as e: return { "ligand": ligand_name, "status": "FAILED", "best_affinity_kcal_per_mol": "", "best_mode": "", "rmsd_lb": "", "rmsd_ub": "", "num_modes_generated": "", "error": str(e), "complex_pdb": "", "scores_csv": "", } def parse_smiles_table(smiles_text: str): ligands = [] for i, line in enumerate(smiles_text.splitlines(), start=1): line = line.strip() if not line: continue if "," in line: parts = [p.strip() for p in line.split(",", 1)] name, smiles = parts[0], parts[1] elif "\t" in line: parts = [p.strip() for p in line.split("\t", 1)] name, smiles = parts[0], parts[1] else: name, smiles = f"SMILES_{i}", line ligands.append({"name": safe_filename(name), "smiles": smiles}) return ligands def main(): st.set_page_config(page_title="Bulamarwa Batch Protein-Ligand Docking Tool", layout="wide") init_state() st.title("Bulamarwa Batch Protein-Ligand Docking Tool") st.caption("Prepared receptor is reused once; multiple ligands are docked with timeout, failure skipping, CSV summary, and ZIP export.") with st.sidebar: st.header("Run settings") exhaustiveness = st.slider("Exhaustiveness", 1, 24, 1, 1) num_modes = st.slider("Number of poses", 1, 10, 1, 1) prep_timeout = st.number_input("Preparation timeout per step (seconds)", min_value=60, max_value=1800, value=240, step=60) vina_timeout = st.number_input("Vina timeout per ligand (seconds)", min_value=60, max_value=7200, value=180, step=60) cpu_threads = st.slider("CPU threads for Vina", 1, 8, 1, 1) st.warning("Fast/stable default: exhaustiveness 4, poses 3. For poor network, dock fewer ligands per run and download ZIP immediately.") if st.button("Clear all inputs and results"): reset_all() required_commands = { "AutoDock Vina": resolve_command("vina"), "Open Babel": resolve_command("obabel"), "Meeko receptor preparation": resolve_command("mk_prepare_receptor.py", "mk_prepare_receptor"), } missing_cmds = [label for label, executable in required_commands.items() if not executable] if missing_cmds: st.error( "Missing required docking component(s): " + ", ".join(missing_cmds) + ". Rebuild the Hugging Face Docker Space using the supplied Dockerfile and requirements.txt." ) st.stop() with st.expander("Installed docking components", expanded=False): for label, executable in required_commands.items(): st.code(f"{label}: {executable}") st.subheader("Step 1: Upload receptor and ligands") protein_upload = st.file_uploader( "Upload protein receptor (PDB or PDBQT)", type=["pdb", "pdbqt"], accept_multiple_files=False, ) ligand_uploads = st.file_uploader( "Upload one or more ligands (SDF, MOL, MOL2, PDB, or PDBQT)", type=["sdf", "mol", "mol2", "pdb", "pdbqt"], accept_multiple_files=True, ) smiles_text = st.text_area( "Optional: paste SMILES, one ligand per line. Format: Name,SMILES or only SMILES", height=120, ) docking_run_mode = st.radio( "Ligand running option", ["Run only one ligand", "Run all uploaded/pasted ligands"], index=0, help="Use 'Run only one ligand' when network is unstable or when testing one compound at a time." ) st.subheader("Step 2: Docking box definition") docking_mode = st.radio( "Choose docking mode", ["Residue-based docking", "Blind docking", "Manual box coordinates"], index=0, ) residue_selection_text = "" padding = 8.0 center = (0.0, 0.0, 0.0) size = (20.0, 20.0, 20.0) if docking_mode == "Residue-based docking": st.code("Examples:\nA:LYS45,ASP46\nA:45-50\nA:LYS45;B:TYR120") residue_selection_text = st.text_area("Residues and chains") 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("Padding around whole protein (Å)", min_value=2.0, value=6.0, step=1.0) st.warning("Blind docking can be slow. Use residue-based docking when possible.") 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") center = (center_x, center_y, center_z) size = (size_x, size_y, size_z) run_disabled = protein_upload is None or (not ligand_uploads and not smiles_text.strip()) if st.button("Run batch docking", type="primary", disabled=run_disabled): try: session_dir = get_session_dir() export_dir = get_export_dir() shutil.rmtree(export_dir, ignore_errors=True) export_dir.mkdir(parents=True, exist_ok=True) protein_name = safe_filename(protein_upload.name) protein_path = session_dir / f"protein_{protein_name}" save_uploaded_file(protein_upload, protein_path) validate_extension(protein_upload.name, SUPPORTED_PROTEIN_EXTS, "Protein") validate_input_file_content(protein_path, "Protein") ligand_paths = [] for lig in ligand_uploads or []: validate_extension(lig.name, SUPPORTED_LIGAND_EXTS, "Ligand") lig_path = session_dir / f"ligand_{safe_filename(lig.name)}" save_uploaded_file(lig, lig_path) validate_input_file_content(lig_path, "Ligand") ligand_paths.append(lig_path) smiles_ligands = parse_smiles_table(smiles_text) if docking_mode == "Blind docking": center, size = compute_blind_docking_box(protein_path, padding=padding, min_size=20.0) size = limit_box_size(size, max_size=25.0) elif docking_mode == "Residue-based docking": center, size = compute_residue_based_box(protein_path, residue_selection_text, padding=padding, min_size=18.0) size = limit_box_size(size, max_size=25.0) else: size = limit_box_size(size, max_size=25.0) current_volume = box_volume(size) if current_volume > 27000: st.error( f"Docking box is still too large: {current_volume} Angstrom^3. " "Reduce Size X/Y/Z below 30 Angstrom." ) st.stop() st.info(f"Docking box center: {center}; size: {size}; volume: {current_volume} Angstrom^3") batch_dir = export_dir / "batch_docking_results" batch_dir.mkdir(parents=True, exist_ok=True) receptor_work = batch_dir / "_receptor_preparation" shutil.rmtree(receptor_work, ignore_errors=True) receptor_work.mkdir(parents=True, exist_ok=True) with st.spinner("Preparing receptor once with Meeko..."): receptor_pdbqt, receptor_source, receptor_info = prepare_receptor_once( receptor_work, protein_path, center, size, timeout=prep_timeout, ) fixed_receptor_pdbqt = batch_dir / "prepared_receptor.pdbqt" fixed_receptor_source = batch_dir / "receptor_source.pdb" if receptor_pdbqt.resolve() != fixed_receptor_pdbqt.resolve(): shutil.copy2(receptor_pdbqt, fixed_receptor_pdbqt) else: fixed_receptor_pdbqt = receptor_pdbqt if receptor_source.resolve() != fixed_receptor_source.resolve(): convert_structure_to_pdb( receptor_source, fixed_receptor_source, timeout=prep_timeout, ) else: fixed_receptor_source = receptor_source (batch_dir / "receptor_preparation_summary.json").write_text( json.dumps(receptor_info, indent=2) ) all_ligands = [("file", p) for p in ligand_paths] all_ligands.extend([("smiles", s) for s in smiles_ligands]) if docking_run_mode == "Run only one ligand": all_ligands = all_ligands[:1] st.info("Single-ligand mode selected. Only the first uploaded/pasted ligand will be docked.") progress = st.progress(0) status_box = st.empty() records = [] for i, (kind, source) in enumerate(all_ligands, start=1): lig_name = source.name if kind == "file" else source["name"] status_box.info(f"Docking ligand {i}/{len(all_ligands)}: {lig_name}") record = dock_single_ligand( ligand_source=source, ligand_kind=kind, receptor_pdbqt=fixed_receptor_pdbqt, receptor_source=fixed_receptor_source, batch_dir=batch_dir, center=center, size=size, exhaustiveness=exhaustiveness, num_modes=num_modes, vina_timeout=vina_timeout, prep_timeout=prep_timeout, cpu_threads=cpu_threads, ) records.append(record) pd.DataFrame(records).to_csv(batch_dir / "batch_docking_summary.csv", index=False) progress.progress(i / len(all_ligands)) summary_df = pd.DataFrame(records) summary_csv = batch_dir / "batch_docking_summary.csv" summary_xlsx = batch_dir / "batch_docking_summary.xlsx" summary_df.to_csv(summary_csv, index=False) summary_df.to_excel(summary_xlsx, index=False) zip_path = export_dir / "batch_docking_results.zip" make_zip(zip_path, batch_dir) st.session_state["run_outputs"] = { "summary_csv": str(summary_csv), "summary_xlsx": str(summary_xlsx), "zip": str(zip_path), "summary_df": records, "center": center, "size": size, } st.success("Batch docking completed. Failed ligands, if any, were skipped and recorded.") except Exception as e: st.error(str(e)) try: export_dir = get_export_dir() batch_dir = export_dir / "batch_docking_results" if batch_dir.exists(): diagnostic_zip = export_dir / "docking_failure_diagnostics.zip" make_zip(diagnostic_zip, batch_dir) with open(diagnostic_zip, "rb") as diagnostic_file: st.download_button( "Download failure diagnostics", diagnostic_file.read(), file_name="docking_failure_diagnostics.zip", mime="application/zip", ) except Exception: pass outputs = st.session_state.get("run_outputs") if outputs: st.subheader("Batch docking summary") df = pd.DataFrame(outputs["summary_df"]) preferred_columns = [ "ligand", "status", "best_mode", "best_affinity_kcal_per_mol", "rmsd_lb", "rmsd_ub", "num_modes_generated", "complex_pdb", "scores_csv", "error", ] existing_columns = [col for col in preferred_columns if col in df.columns] remaining_columns = [col for col in df.columns if col not in existing_columns] df = df[existing_columns + remaining_columns] st.dataframe(df, use_container_width=True) st.metric("Successful ligands", int((df["status"] == "SUCCESS").sum())) st.metric("Failed ligands", int((df["status"] == "FAILED").sum())) successful_df = df[df["status"] == "SUCCESS"].copy() if not successful_df.empty: st.subheader("Download individual best protein-ligand complexes") for idx, row in successful_df.iterrows(): complex_path = Path(str(row.get("complex_pdb", ""))) if complex_path.exists(): ligand_label = safe_filename(str(row.get("ligand", f"ligand_{idx}"))) with open(complex_path, "rb") as complex_file: st.download_button( label=f"Download best complex: {ligand_label}", data=complex_file.read(), file_name=f"{ligand_label}_best_protein_ligand_complex.pdb", mime="chemical/x-pdb", key=f"download_complex_{idx}", ) c1, c2, c3 = st.columns(3) with c1: with open(outputs["summary_csv"], "rb") as f: st.download_button( "Download summary CSV", f.read(), file_name="batch_docking_summary.csv", mime="text/csv", ) with c2: with open(outputs["summary_xlsx"], "rb") as f: st.download_button( "Download summary Excel", f.read(), file_name="batch_docking_summary.xlsx", mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) with c3: with open(outputs["zip"], "rb") as f: st.download_button( "Download all results ZIP", f.read(), file_name="batch_docking_results.zip", mime="application/zip", ) if __name__ == "__main__": main()