Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files16 unmodified lines1718192021222324252627282930313233343536373839409 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091103 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701714 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971 unmodified line1992002012022032042052062072082092102112122132142152162172182192202212222232246 unmodified lines2312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792803 unmodified lines2842852862872882892904 unmodified lines2952962972982993003014 unmodified lines30630730830931031131231331431531631731831932032132232332432532632732832933033133216 unmodified lines3493503513523533543553563573583593603613621 unmodified line36436536636736836937037137237337437537614 unmodified lines3913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634641 unmodified line4664674684694704714724734744754764774784794804814824834844854864874884894904917 unmodified lines4995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535544 unmodified lines55956056156256356456556656756856957057157257357457557619 unmodified lines59659759859960060160260360460560660760860961061161261361461561661718 unmodified lines6366376386396406416428 unmodified lines6516526536546556566575 unmodified lines6636646656666676686696706716727 unmodified lines6806816826836846856867 unmodified lines6946956966976986997007017027037047057067071 unmodified line7097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437446 unmodified lines75175275375475575675713 unmodified lines7717727737747757767777787797807817827837846 unmodified lines79179279379479579679713 unmodified lines8118128138148158168178188198208218222 unmodified lines8258268278288298308318328338348358368375 unmodified lines8438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639646 unmodified lines97197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102915 unmodified lines1045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114516 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)# ----------------------------# Data classes# ----------------------------@dataclassclass AtomRecord:9 unmodified linesline: str# ----------------------------# Command helpers# ----------------------------def ensure_command(cmd: str) -> bool:return shutil.which(cmd) is not Nonedef run_cmd(cmd: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess: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"] = Noneif "saved_protein_path" not in st.session_state:st.session_state["saved_protein_path"] = Noneif "saved_ligand_path" not in st.session_state:st.session_state["saved_ligand_path"] = Noneif "saved_protein_name" not in st.session_state:st.session_state["saved_protein_name"] = Noneif "saved_ligand_name" not in st.session_state:st.session_state["saved_ligand_name"] = Noneif "upload_notice" not in st.session_state:st.session_state["upload_notice"] = Nonedef get_session_dir() -> Path:session_dir = UPLOAD_ROOT / st.session_state["session_id"]session_dir.mkdir(parents=True, exist_ok=True)return session_dirdef get_export_dir() -> Path:export_dir = EXPORT_ROOT / st.session_state["session_id"]export_dir.mkdir(parents=True, exist_ok=True)return export_dirdef safe_filename(name: str) -> str:3 unmodified linesdef 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)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",]: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())return out_pathdef 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.nameif ligand_upload is not None:ligand_name = safe_filename(ligand_upload.name)ligand_path = session_dir / f"ligand_{ligand_name}"4 unmodified linesdef get_saved_protein_path() -> Optional[Path]:p = st.session_state.get("saved_protein_path")if p and Path(p).exists():return Path(p)return Nonedef 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# ----------------------------# 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 lineif not (line.startswith("ATOM") or line.startswith("HETATM")):continuetry: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,line=line,))6 unmodified linesselections: List[Tuple[str, int, Optional[str]]] = []if not selection_text.strip():return selectionsblocks = [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.")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))if end < start:raise ValueError(f"Invalid range '{item}' in block '{block}'.")for rnum in range(start, end + 1):selections.append((chain, rnum, None))continuem_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))continuem_num = re.fullmatch(r"(\d+)", item)if m_num:selections.append((chain, int(m_num.group(1)), None))continueraise ValueError(f"Could not parse residue item '{item}'. Use A:45, A:45-50, or A:LYS45.")return selections3 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 linescontinuematched_atoms.append(atom)breakreturn matched_atoms4 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, size16 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.")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 lineif key not in seen:seen.add(key)matched_rows.append({"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_df14 unmodified linesfout.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 = {"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:return letters[:2].capitalize()return letters[0].capitalize()def clean_receptor_pdb_for_meeko(infile: Path, outfile: Path) -> None:kept = 0with open(infile, "r", errors="ignore") as fin, open(outfile, "w") as fout:for line in fin:if not line.startswith("ATOM"):continueline = 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()element = line[76:78].strip()if res_name in {"HOH", "WAT"}:continueif altloc not in {"", "A"}:continueif not element:element = infer_element_from_atom_name(atom_name)if not element:continuenewline = line[:76] + f"{element:>2}" + line[78:]fout.write(newline + "\n")kept += 1fout.write("END\n")if kept == 0:raise ValueError("No valid ATOM records remained after receptor cleaning.")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:raise RuntimeError(f"Invalid receptor PDBQT: found ligand-only tag(s): {', '.join(found)}")def prepare_receptor_pdbqt(1 unmodified lineprotein_file: Path,center: Tuple[float, float, float],size: Tuple[float, float, float],) -> Tuple[Path, Path]: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_fileif 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)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.")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)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"STDOUT:\n{result.stdout}\n"f"STDERR:\n{result.stderr}")validate_receptor_pdbqt(pdbqt_path)return pdbqt_path, cleaned_pdb# ----------------------------# 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.")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: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 Nonesuffix = 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 lineselif 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.")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:raise ValueError("Could not generate a 3D conformer for the ligand.")AllChem.UFFOptimizeMolecule(mol, maxIters=500)return mol, suffix.lstrip(".")19 unmodified linesout_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}")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 lineslines = []in_first_model = Falsesaw_model = Falsewith open(pdbqt_path, "r", errors="ignore") as f:for line in f:if line.startswith("MODEL"):8 unmodified lineslines.append(line)else:lines.append(line)with open(out_path, "w") as out:out.writelines(lines)out.write("END\n")5 unmodified linesfor 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))except Exception:continuereturn coords7 unmodified linesreceptor_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 linezf.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}")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"}: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 lineswith tempfile.TemporaryDirectory(prefix="dockapp_job_") as tmpdir:work_dir = Path(tmpdir)receptor_pdbqt, receptor_source = 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 ""))if result.returncode != 0 or not docked_pdbqt.exists():raise RuntimeError("Docking failed.\n"f"Command: {' '.join(cmd)}\n"f"STDOUT:\n{result.stdout}\n"f"STDERR:\n{result.stderr}")6 unmodified linesresidues_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)),}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"])if residue_pdb.exists():out_map["active_site_pdb"] = export_dir / "active_site_residues.pdb"5 unmodified linesreturn 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.")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")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.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")if save_uploads_clicked: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"])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)")elif smiles_text.strip():st.success("SMILES input ready.")else:st.info("No saved ligand 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 linessize_x = size_y = size_z = 20.0if 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",)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: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 = Noneif docking_mode == "Blind docking":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,)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,}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}")if __name__ == "__main__":16 unmodified lines171819202122232425262728293031323334353637383940414243449 unmodified lines5455565758596061626364656667686970717273747576777879808182838485863 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241254 unmodified lines1301311321331341351361371381391401411421431 unmodified line1451461471481491501511521531541551561571581591601616 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002013 unmodified lines2052062072082092104 unmodified lines2152162172182192204 unmodified lines22522622722822923023123223323423523623723823924024124224324424524616 unmodified lines2632642652662672682692702712722731 unmodified line27527627727827928028128214 unmodified lines2972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913921 unmodified line3943953963973983994004014024034044054064074084094104114124134144154167 unmodified lines4244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654 unmodified lines47047147247347447547647747847948048148248319 unmodified lines50350450550650750850951051151251351418 unmodified lines5335345355365375388 unmodified lines5475485495505515525 unmodified lines5585595605615625635645655665675687 unmodified lines5765775785795805817 unmodified lines5895905915925935945955965971 unmodified line5996006016026036046056066076086096106116126136146156166176186196206216 unmodified lines62862963063163263363463563613 unmodified lines6506516526536546556566576586596606616626636646656666676686 unmodified lines67567667767867968013 unmodified lines6946956966976986997007017027037042 unmodified lines7077087097107117127137147157167177187197207215 unmodified lines7277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038046 unmodified lines81181281381481581681781881982082182282382482582682782882983083183283383483583683783883984015 unmodified lines85685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590616 unmodified linesfrom rdkit.Chem import AllChemSUPPORTED_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",}@dataclassclass AtomRecord:9 unmodified linesline: strdef ensure_command(cmd: str) -> bool:return shutil.which(cmd) is not Nonedef run_cmd(cmd: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess:return subprocess.run(cmd, cwd=cwd, text=True, capture_output=True, check=False)def init_state() -> 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:p = UPLOAD_ROOT / st.session_state["session_id"]p.mkdir(parents=True, exist_ok=True)return pdef get_export_dir() -> Path:p = EXPORT_ROOT / st.session_state["session_id"]p.mkdir(parents=True, exist_ok=True)return pdef safe_filename(name: str) -> str:3 unmodified linesdef reset_all() -> None: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"]:if key in st.session_state:del st.session_state[key]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_pathdef 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.nameif ligand_upload is not None:ligand_name = safe_filename(ligand_upload.name)ligand_path = session_dir / f"ligand_{ligand_name}"4 unmodified linesdef get_saved_protein_path() -> Optional[Path]:p = st.session_state.get("saved_protein_path")return Path(p) if p and Path(p).exists() else Nonedef get_saved_ligand_path() -> Optional[Path]:p = st.session_state.get("saved_ligand_path")return Path(p) if p and Path(p).exists() else Nonedef parse_pdb_like_atoms(file_path: Path) -> List[AtomRecord]:atoms: List[AtomRecord] = []with open(file_path, "r", errors="ignore") as f:1 unmodified lineif not (line.startswith("ATOM") or line.startswith("HETATM")):continuetry: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,))6 unmodified linesselections: List[Tuple[str, int, Optional[str]]] = []if not selection_text.strip():return selectionsblocks = [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()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 = 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))continuem_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()))continuem_num = re.fullmatch(r"(\d+)", item)if m_num:selections.append((chain, int(m_num.group(1)), None))continueraise ValueError(f"Could not parse residue item '{item}'.")return selections3 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 linescontinuematched_atoms.append(atom)breakreturn matched_atoms4 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, size16 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.")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 lineif key not in seen:seen.add(key)matched_rows.append({"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_df14 unmodified linesfout.write("END\n")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 = {"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: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,}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"] += 1continueline = 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"] += 1continueif altloc not in {"", "A"}:stats["dropped_altloc"] += 1continueif not element:element = infer_element_from_atom_name(atom_name)if element.upper() == "H" or atom_name.upper().startswith("H"):stats["dropped_hydrogen"] += 1continueif res_name in AA_RENAMES:res_name = AA_RENAMES[res_name]line = line[:17] + f"{res_name:>3}" + line[20:]stats["renamed_residue"] += 1if res_name not in STANDARD_AA:stats["dropped_nonstandard"] += 1continueif not element:stats["dropped_nonstandard"] += 1continueline = line[:76] + f"{element:>2}" + line[78:]fout.write(line + "\n")stats["kept_atoms"] += 1fout.write("TER\nEND\n")if stats["kept_atoms"] == 0:raise ValueError("No valid standard protein atoms remained after strict receptor cleaning.")return statsdef validate_receptor_pdbqt(pdbqt_path: Path) -> None: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(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 lineprotein_file: Path,center: Tuple[float, float, float],size: Tuple[float, float, float],) -> 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, {"kept_atoms": -1}if protein_suffix != ".pdb":raise ValueError("Protein must be PDB or PDBQT.")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.")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"]pdbqt_path = next((p for p in candidates if p.exists()), None)if result.returncode != 0 or pdbqt_path is None:raise RuntimeError("Receptor preparation with mk_prepare_receptor.py failed.\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, clean_statsdef validate_ligand_pdbqt(pdbqt_path: Path) -> None:text = pdbqt_path.read_text(errors="ignore")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)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 Nonesuffix = 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 lineselif 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 the ligand file.")if mol.GetNumConformers() == 0:mol = Chem.AddHs(mol)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 linesout_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(f"Ligand preparation failed.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")validate_ligand_pdbqt(out_pdbqt)return out_pdbqtVINA_TABLE_RE = re.compile(r"^\s*(\d+)\s+(-?\d+\.\d+)\s+([0-9.]+)\s+([0-9.]+)\s*$")18 unmodified lineslines = []in_first_model = Falsesaw_model = Falsewith open(pdbqt_path, "r", errors="ignore") as f:for line in f:if line.startswith("MODEL"):8 unmodified lineslines.append(line)else:lines.append(line)with open(out_path, "w") as out:out.writelines(lines)out.write("END\n")5 unmodified linesfor line in f:if line.startswith(("ATOM", "HETATM")):try:coords.append((float(line[30:38].strip()),float(line[38:46].strip()),float(line[46:54].strip()),))except Exception:continuereturn coords7 unmodified linesreceptor_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"]))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 linezf.write(fp, arcname=fp.name)def validate_extension(name: str, allowed: set[str], label: str) -> None: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) -> 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.")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.")def run_docking(protein_file: Path,ligand_file: Optional[Path],6 unmodified lineswith tempfile.TemporaryDirectory(prefix="dockapp_job_") as tmpdir:work_dir = Path(tmpdir)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(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 linesresidues_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()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",}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 linesreturn out_mapdef main() -> None:st.set_page_config(page_title="Protein-Ligand Docking Tool", layout="wide")init_state()st.title("Protein-Ligand Docking Tool")st.caption("Save uploads first, then run docking with stricter receptor cleaning.")with st.sidebar:st.header("Run settings")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))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",)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",)smiles_text = st.text_area("Or paste ligand SMILES", key="smiles_text")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.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()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.info("Ligand: SMILES input")else: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 linessize_x = size_y = size_z = 20.0if 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", 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: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:residue_match_df = Noneif docking_mode == "Blind docking":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)else:center = (center_x, center_y, center_z)15 unmodified lines"center": center,"size": size,"mode": docking_mode,"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: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