Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files120 unmodified lines121122123124125126127128129130131132148 unmodified lines2812822832842852869 unmodified lines296297298299300301218 unmodified lines5205215225235245255265275285293 unmodified lines5335345355365375385395405415425435445455463 unmodified lines550551552553554555556124 unmodified lines68168268368468568668768868969069169269369469569669769869970070170270370470570670738 unmodified lines74674774874975075175275375475575675775811 unmodified lines7707717727737747752 unmodified lines7787797807817827834 unmodified lines78878979079179279379410 unmodified lines8058068078088098108118128138148158168178188198208218228238248258268278288298308318328339 unmodified lines8438448458468478488491 unmodified line8518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858863 unmodified lines89089189289389489589689789889990090169 unmodified lines9719729739749759762 unmodified lines9799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102216 unmodified lines10391040104110421043104413 unmodified lines1058105910601061106210631064106510661067106810691070107110721073107410751076120 unmodified linesdef 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}"148 unmodified linesselections = 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.")9 unmodified linesmatched_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_df218 unmodified linescleaned_pdb = work_dir / "receptor_cleaned_strict.pdb"clean_stats = strict_clean_receptor_pdb(protein_file, cleaned_pdb)# 1. Try whole cleaned receptorok, pdbqt_path, log_text = try_meeko_prepare(cleaned_pdb, work_dir, center, size, "receptor_full")if ok:return pdbqt_path, cleaned_pdb, {"strategy": "full_cleaned_receptor",3 unmodified linesresidues_by_chain = group_residues_from_pdb(cleaned_pdb)# 2. Try each chain separatelychain_attempt_logs = {}for chain, residues in sorted(residues_by_chain.items(), key=lambda x: len(x[1]), reverse=True):chain_pdb = work_dir / f"receptor_chain_{chain}.pdb"write_filtered_pdb(cleaned_pdb, chain_pdb, keep_chains={chain})ok, pdbqt_path, chain_log = try_meeko_prepare(chain_pdb, work_dir, center, size, f"receptor_chain_{chain}")chain_attempt_logs[chain] = chain_logif ok:return pdbqt_path, chain_pdb, {3 unmodified lines"selected_chain": chain,}# 3. Rescue: one-residue-at-a-time removal for each chainfor chain, residues in sorted(residues_by_chain.items(), key=lambda x: len(x[1]), reverse=True):if len(residues) < 2:continue124 unmodified linesreturn pd.DataFrame(rows)def split_first_model_pdbqt(pdbqt_path: Path, out_path: Path) -> None:lines = []in_first_model = Falsesaw_model = Falsewith open(pdbqt_path, "r", errors="ignore") as f:for line in f:if line.startswith("MODEL"):saw_model = Trueparts = line.split()in_first_model = len(parts) > 1 and parts[1] == "1"continueif line.startswith("ENDMDL") and in_first_model:breakif 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 parse_xyz_from_pdbqt(file_path: Path) -> List[Tuple[float, float, float]]:38 unmodified linesreturn 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:if fp.exists():zf.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:11 unmodified linesraise ValueError(f"{label} file does not appear to contain valid atomic records.")def run_docking(protein_file: Path,ligand_file: Optional[Path],2 unmodified linessize: Tuple[float, float, float],exhaustiveness: int,num_modes: int,) -> Dict[str, Path]:with tempfile.TemporaryDirectory(prefix="dockapp_job_") as tmpdir:work_dir = Path(tmpdir)4 unmodified linesligand_pdbqt = prepare_ligand_pdbqt(work_dir, ligand_file, smiles_text)docked_pdbqt = work_dir / "docked_out.pdbqt"log_path = work_dir / "docking.log"cmd = ["vina",10 unmodified lines"--out", str(docked_pdbqt),]result = run_cmd(cmd, cwd=str(work_dir))log_path.write_text("Receptor preparation info:\n"+ json.dumps(receptor_prep_info, indent=2)+ "\n\nSTDOUT:\n"+ (result.stdout or "")+ "\nSTDERR:\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 preparation info: {json.dumps(receptor_prep_info)}\n"f"STDOUT:\n{result.stdout}\n"f"STDERR:\n{result.stderr}")scores_df = parse_vina_log(log_path)best_pose = work_dir / "best_pose_model1.pdbqt"split_first_model_pdbqt(docked_pdbqt, best_pose)residues_df = infer_active_site_residues(receptor_source, best_pose, cutoff=4.5)residues_csv = work_dir / "active_site_residues.csv"scores_csv = work_dir / "docking_scores.csv"9 unmodified lines]write_residue_subset_pdb(receptor_source, residue_keys, residue_pdb)best_aff = float(scores_df.iloc[0]["affinity_kcal_per_mol"]) if not scores_df.empty else Nonepayload = {"protein_file": protein_file.name,"ligand_file": ligand_file.name if ligand_file else "SMILES input",1 unmodified line"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_preparation": receptor_prep_info,}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","scores_csv": export_dir / "docking_scores.csv","residues_csv": export_dir / "active_site_residues.csv","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"shutil.copy2(residue_pdb, out_map["active_site_pdb"])zip_path = export_dir / "docking_results_bundle.zip"make_zip(zip_path, list(out_map.values()))out_map["zip"] = zip_pathreturn out_map3 unmodified linesinit_state()st.title("Protein-Ligand Docking Tool")st.caption("Save uploads first, then run docking with robust receptor rescue logic.")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()69 unmodified lines)residue_selection_text = ""padding = 8.0center_x = center_y = center_z = 0.0size_x = size_y = size_z = 20.02 unmodified linesst.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)size = (size_x, size_y, size_z)with st.spinner("Running docking..."):outputs = run_docking(protein_file=protein_path,ligand_file=ligand_path,smiles_text=smiles_text,center=center,size=size,exhaustiveness=exhaustiveness,num_modes=num_modes,)st.session_state["run_outputs"] = {16 unmodified linesscores_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")13 unmodified linesst.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")120 unmodified lines121122123124125126127128129130131132133134148 unmodified lines2832842852862872882899 unmodified lines299300301302303304305218 unmodified lines5245255265275285295303 unmodified lines5345355365375385395405415425435443 unmodified lines548549550551552553124 unmodified lines67867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072138 unmodified lines76076176276376476511 unmodified lines7777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578582 unmodified lines8618628638648658668674 unmodified lines87287387487587687787810 unmodified lines8898908918928938948958968978988999009019029039049059069079089099109119129139149159 unmodified lines9259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689691 unmodified line97197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310243 unmodified lines102810291030103110321033103410351036103710381039104069 unmodified lines11101111111211131114111511162 unmodified lines1119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118016 unmodified lines119711981199120012011202120313 unmodified lines12171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260120 unmodified linesdef 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}"148 unmodified linesselections = 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.")9 unmodified linesmatched_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_df218 unmodified linescleaned_pdb = work_dir / "receptor_cleaned_strict.pdb"clean_stats = strict_clean_receptor_pdb(protein_file, cleaned_pdb)ok, pdbqt_path, log_text = try_meeko_prepare(cleaned_pdb, work_dir, center, size, "receptor_full")if ok:return pdbqt_path, cleaned_pdb, {"strategy": "full_cleaned_receptor",3 unmodified linesresidues_by_chain = group_residues_from_pdb(cleaned_pdb)chain_attempt_logs = {}for chain, residues in sorted(residues_by_chain.items(), key=lambda x: len(x[1]), reverse=True):chain_pdb = work_dir / f"receptor_chain_{chain}.pdb"write_filtered_pdb(cleaned_pdb, chain_pdb, keep_chains={chain})ok, pdbqt_path, chain_log = try_meeko_prepare(chain_pdb, work_dir, center, size, f"receptor_chain_{chain}")chain_attempt_logs[chain] = chain_logif ok:return pdbqt_path, chain_pdb, {3 unmodified lines"selected_chain": chain,}for chain, residues in sorted(residues_by_chain.items(), key=lambda x: len(x[1]), reverse=True):if len(residues) < 2:continue124 unmodified linesreturn pd.DataFrame(rows)def split_pose_models(pdbqt_path: Path, out_dir: Path, max_modes: int = 10) -> List[Path]:out_dir.mkdir(parents=True, exist_ok=True)pose_files: List[Path] = []current_lines: List[str] = []current_mode: Optional[int] = Nonesaw_model = Falsewith open(pdbqt_path, "r", errors="ignore") as f:for line in f:if line.startswith("MODEL"):saw_model = Trueparts = line.split()current_mode = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else len(pose_files) + 1current_lines = []continueif line.startswith("ENDMDL"):if current_mode is not None and len(pose_files) < max_modes:out_path = out_dir / f"pose_mode_{current_mode}.pdbqt"with open(out_path, "w") as out:out.writelines(current_lines)out.write("END\n")pose_files.append(out_path)current_lines = []current_mode = Nonecontinueif saw_model:if current_mode is not None:current_lines.append(line)if not saw_model:out_path = out_dir / "pose_mode_1.pdbqt"shutil.copy2(pdbqt_path, out_path)pose_files.append(out_path)return pose_filesdef parse_xyz_from_pdbqt(file_path: Path) -> List[Tuple[float, float, float]]:38 unmodified linesreturn pd.DataFrame(sorted(residues.values(), key=lambda x: x["min_distance_A"]))def validate_extension(name: str, allowed: set[str], label: str) -> None:suffix = Path(name).suffix.lower()if suffix not in allowed:11 unmodified linesraise ValueError(f"{label} file does not appear to contain valid atomic records.")def convert_structure_to_pdb(input_path: Path, output_path: Path) -> Path:if input_path.suffix.lower() == ".pdb":shutil.copy2(input_path, output_path)return output_pathif not ensure_command("obabel"):raise RuntimeError("obabel is required to convert structures to PDB format.")result = run_cmd(["obabel", str(input_path), "-O", str(output_path)])if result.returncode != 0 or not output_path.exists():raise RuntimeError(f"Failed to convert {input_path.name} to PDB.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")return output_pathdef combine_protein_and_ligand_pdb(receptor_pdb: Path,ligand_pdb: Path,complex_pdb: Path,ligand_resname: str = "LIG",ligand_chain: str = "Z",) -> None:serial = 1ligand_resseq = 1with open(complex_pdb, "w") as out:with open(receptor_pdb, "r", errors="ignore") as fin:for line in fin:if line.startswith(("ATOM", "HETATM")):line = line.rstrip("\n")if len(line) < 80:line = line.ljust(80)new_line = f"{line[:6]}{serial:5d}{line[11:]}"out.write(new_line + "\n")serial += 1out.write("TER\n")with open(ligand_pdb, "r", errors="ignore") as fin:for line in fin:if not line.startswith(("ATOM", "HETATM")):continueline = line.rstrip("\n")if len(line) < 80:line = line.ljust(80)atom_name = line[12:16]x = line[30:38]y = line[38:46]z = line[46:54]occ = line[54:60] if len(line) >= 60 else " 1.00"bfac = line[60:66] if len(line) >= 66 else " 0.00"element = line[76:78].strip() if len(line) >= 78 else ""if not element:atom_name_clean = line[12:16].strip()element = infer_element_from_atom_name(atom_name_clean)new_line = (f"HETATM{serial:5d} {atom_name:<4}{ligand_resname:>3} {ligand_chain}"f"{ligand_resseq:4d} {x}{y}{z}{occ}{bfac} {element:>2}")out.write(new_line + "\n")serial += 1out.write("END\n")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:if fp.exists():zf.write(fp, arcname=fp.name)def run_docking(protein_file: Path,ligand_file: Optional[Path],2 unmodified linessize: Tuple[float, float, float],exhaustiveness: int,num_modes: int,export_top_complexes: int = 3,) -> Dict[str, Path]:with tempfile.TemporaryDirectory(prefix="dockapp_job_") as tmpdir:work_dir = Path(tmpdir)4 unmodified linesligand_pdbqt = prepare_ligand_pdbqt(work_dir, ligand_file, smiles_text)docked_pdbqt = work_dir / "docked_out.pdbqt"vina_stdout_log = work_dir / "vina_stdout.log"cmd = ["vina",10 unmodified lines"--out", str(docked_pdbqt),]result = run_cmd(cmd, cwd=str(work_dir))vina_stdout_log.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}")scores_df = parse_vina_log(vina_stdout_log)if scores_df.empty:raise RuntimeError("Docking completed, but no binding affinity table could be parsed from Vina output.")pose_dir = work_dir / "poses"pose_pdbqt_files = split_pose_models(docked_pdbqt, pose_dir, max_modes=num_modes)if not pose_pdbqt_files:raise RuntimeError("Could not extract docked pose models from the Vina output.")best_pose_pdbqt = pose_pdbqt_files[0]residues_df = infer_active_site_residues(receptor_source, best_pose_pdbqt, cutoff=4.5)residues_csv = work_dir / "active_site_residues.csv"scores_csv = work_dir / "docking_scores.csv"9 unmodified lines]write_residue_subset_pdb(receptor_source, residue_keys, residue_pdb)receptor_pdb_for_complex = work_dir / "receptor_for_complex.pdb"convert_structure_to_pdb(receptor_source, receptor_pdb_for_complex)complexes_dir = work_dir / "complexes"complexes_dir.mkdir(parents=True, exist_ok=True)export_top_complexes = max(1, min(export_top_complexes, len(pose_pdbqt_files), len(scores_df)))complex_rows = []exported_files: List[Path] = []for idx in range(export_top_complexes):mode_no = int(scores_df.iloc[idx]["mode"])affinity = float(scores_df.iloc[idx]["affinity_kcal_per_mol"])pose_pdbqt = pose_pdbqt_files[idx]pose_pdb = complexes_dir / f"mode_{mode_no}_ligand_pose.pdb"convert_structure_to_pdb(pose_pdbqt, pose_pdb)complex_pdb = complexes_dir / f"mode_{mode_no}_protein_ligand_complex.pdb"combine_protein_and_ligand_pdb(receptor_pdb_for_complex, pose_pdb, complex_pdb)complex_rows.append({"mode": mode_no,"affinity_kcal_per_mol": affinity,"ligand_pose_pdbqt": pose_pdbqt.name,"ligand_pose_pdb": pose_pdb.name,"complex_pdb": complex_pdb.name,})exported_files.extend([pose_pdbqt, pose_pdb, complex_pdb])complexes_csv = work_dir / "top_complexes_summary.csv"complexes_df = pd.DataFrame(complex_rows)complexes_df.to_csv(complexes_csv, index=False)log_path = work_dir / "docking.log"best_aff = float(scores_df.iloc[0]["affinity_kcal_per_mol"])payload = {"protein_file": protein_file.name,"ligand_file": ligand_file.name if ligand_file else "SMILES input",1 unmodified line"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)),"exported_top_complexes": export_top_complexes,"receptor_preparation": receptor_prep_info,}summary_json.write_text(json.dumps(payload, indent=2))log_text = ("Receptor preparation info:\n"+ json.dumps(receptor_prep_info, indent=2)+ "\n\nVina command:\n"+ " ".join(cmd)+ "\n\nVina STDOUT/STDERR:\n"+ vina_stdout_log.read_text(errors="ignore"))log_path.write_text(log_text)export_dir = get_export_dir()out_map = {"docked_pdbqt": export_dir / "docked_out.pdbqt","best_pose_pdbqt": export_dir / "best_pose_model1.pdbqt","best_complex_pdb": export_dir / "best_protein_ligand_complex.pdb","best_pose_pdb": export_dir / "best_ligand_pose.pdb","scores_csv": export_dir / "docking_scores.csv","complexes_csv": export_dir / "top_complexes_summary.csv","residues_csv": export_dir / "active_site_residues.csv","summary_json": export_dir / "summary.json","log_txt": export_dir / "docking.log",}shutil.copy2(docked_pdbqt, out_map["docked_pdbqt"])shutil.copy2(best_pose_pdbqt, out_map["best_pose_pdbqt"])shutil.copy2(complexes_dir / f"mode_{complex_rows[0]['mode']}_ligand_pose.pdb", out_map["best_pose_pdb"])shutil.copy2(complexes_dir / f"mode_{complex_rows[0]['mode']}_protein_ligand_complex.pdb", out_map["best_complex_pdb"])shutil.copy2(scores_csv, out_map["scores_csv"])shutil.copy2(complexes_csv, out_map["complexes_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"shutil.copy2(residue_pdb, out_map["active_site_pdb"])for fp in exported_files:dst = export_dir / fp.nameshutil.copy2(fp, dst)zip_path = export_dir / "docking_results_bundle.zip"make_zip(zip_path, list(out_map.values()) + [export_dir / fp.name for fp in exported_files if (export_dir / fp.name).exists()])out_map["zip"] = zip_pathreturn out_map3 unmodified linesinit_state()st.title("Protein-Ligand Docking Tool")st.caption("Save uploads first, then run docking and export top protein–ligand complexes.")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)export_top_complexes = st.slider("Export top complexes", 1, 10, 3, 1)if st.button("Clear all inputs and results"):reset_all()69 unmodified lines)residue_selection_text = ""residue_match_df = Nonepadding = 8.0center_x = center_y = center_z = 0.0size_x = size_y = size_z = 20.02 unmodified linesst.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("Padding around whole protein (Å)", min_value=2.0, value=8.0, step=1.0)else:c1, c2, c3 = st.columns(3)with c1:center_x = st.number_input("Center X", value=0.0, step=1.0)size_x = st.number_input("Size X", min_value=5.0, value=20.0, step=1.0)with c2:center_y = st.number_input("Center Y", value=0.0, step=1.0)size_y = st.number_input("Size Y", min_value=5.0, value=20.0, step=1.0)with c3:center_z = st.number_input("Center Z", value=0.0, step=1.0)size_z = st.number_input("Size Z", min_value=5.0, value=20.0, step=1.0)if st.button("Run docking"):try:protein_path = get_saved_protein_path()ligand_path = get_saved_ligand_path()if protein_path is None:raise ValueError("Protein file has not been saved yet.")validate_input_file_content(protein_path, "Protein")if ligand_path is not None:validate_input_file_content(ligand_path, "Ligand")elif not smiles_text.strip():raise ValueError("Provide a ligand file or a SMILES string.")if docking_mode == "Residue-based docking":center, size, residue_match_df = compute_residue_based_box(protein_path,residue_selection_text,padding=padding,min_size=18.0,)elif docking_mode == "Blind docking":center, size = compute_blind_docking_box(protein_path,padding=padding,min_size=20.0,)else:center = (float(center_x), float(center_y), float(center_z))size = (float(size_x), float(size_y), float(size_z))with st.spinner("Running docking..."):outputs = run_docking(protein_file=protein_path,ligand_file=ligand_path,smiles_text=smiles_text.strip(),center=center,size=size,exhaustiveness=exhaustiveness,num_modes=num_modes,export_top_complexes=export_top_complexes,)st.session_state["run_outputs"] = {16 unmodified linesscores_df = pd.read_csv(outputs["scores_csv"])residues_df = pd.read_csv(outputs["residues_csv"])complexes_df = pd.read_csv(outputs["complexes_csv"])summary = json.loads(outputs["summary_json"].read_text())st.subheader("Computed docking box")13 unmodified linesst.subheader("Docking score table")st.dataframe(scores_df, use_container_width=True)st.subheader("Exported top protein–ligand complexes")st.dataframe(complexes_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")d1, d2, d3 = st.columns(3)with d1:with open(outputs["best_complex_pdb"], "rb") as f:st.download_button("Download best complex PDB",f.read(),file_name="best_protein_ligand_complex.pdb",mime="chemical/x-pdb",)with d2:with open(outputs["best_pose_pdb"], "rb") as f:st.download_button("Download best ligand pose PDB",f.read(),file_name="best_ligand_pose.pdb",mime="chemical/x-pdb",)with d3: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")
qsar_core_streamlit.py+267-83