Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files482 unmodified lines48348448548648748848949049149249349429 unmodified lines5245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006015 unmodified lines6076086096106116121 unmodified line614615616617618619620621622623624625626627628482 unmodified lines}def prepare_receptor_once(work_dir: Path, protein_file: Path, center, size, timeout=600):"""Prepare one rigid receptor PDBQT using current Meeko syntax.The function deliberately does not use Open Babel as a receptor-PDBQT fallback.A failed Meeko conversion is stopped with a detailed diagnostic log instead ofpassing an empty or ligand-style PDBQT file to AutoDock Vina."""work_dir.mkdir(parents=True, exist_ok=True)suffix = protein_file.suffix.lower()29 unmodified linesmeeko = resolve_command("mk_prepare_receptor.py", "mk_prepare_receptor")if not meeko:raise RuntimeError("Meeko receptor preparation executable was not found. Install meeko==0.7.1 ""and confirm that mk_prepare_receptor.py or mk_prepare_receptor is on PATH.")receptor_pdbqt = work_dir / "prepared_receptor.pdbqt"attempts = [{"name": "strict", "delete_bad_res": False},{"name": "delete_bad_res", "delete_bad_res": True},]attempt_reports = []for attempt_index, attempt in enumerate(attempts, start=1):receptor_pdbqt.unlink(missing_ok=True)command = [meeko,"--read_pdb",str(receptor_input_pdb),"--write_pdbqt",str(receptor_pdbqt),"--default_altloc","A","--box_center",str(center[0]),str(center[1]),str(center[2]),"--box_size",str(size[0]),str(size[1]),str(size[2]),]if attempt["delete_bad_res"]:command.append("--delete_bad_res")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)# Some Meeko builds may add a rigid suffix. Normalize any valid output# to the exact path used by the rest of the application.if result.returncode == 0 and not receptor_pdbqt.exists():generated_candidates = sorted(work_dir.glob("prepared_receptor*.pdbqt"))generated = next((p for p in generated_candidates if p.stat().st_size > 200), None)if generated is not None:shutil.copy2(generated, receptor_pdbqt)report = {"attempt": attempt["name"],"command": command,"returncode": result.returncode,"stdout_tail": _as_text(result.stdout)[-2000:],"stderr_tail": _as_text(result.stderr)[-4000:],"output_exists": receptor_pdbqt.exists(),"output_size_bytes": receptor_pdbqt.stat().st_size if receptor_pdbqt.exists() else 0,}if result.returncode == 0 and receptor_pdbqt.exists():try:validation = validate_receptor_pdbqt(receptor_pdbqt)report["validation"] = validationattempt_reports.append(report)return receptor_pdbqt, cleaned_pdb, {"strategy": "meeko_current_cli","meeko_executable": meeko,"successful_attempt": attempt["name"],"cleaning_stats": clean_stats,"cleaned_atom_count": cleaned_atom_count,"protonation": protonation_info,"validation": validation,"attempts": attempt_reports,}except Exception as validation_error:report["validation_error"] = str(validation_error)attempt_reports.append(report)5 unmodified lines"cleaning_stats": clean_stats,"cleaned_atom_count": cleaned_atom_count,"protonation": protonation_info,"attempts": attempt_reports,},indent=2,1 unmodified lineencoding="utf-8",)last_stderr = 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"Diagnostic files were saved in {work_dir}.\n\n"f"Last Meeko error:\n{last_stderr}")def ligand_mol_from_input(ligand_file: Path):suffix = ligand_file.suffix.lower()482 unmodified lines48348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163229 unmodified lines6626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607615 unmodified lines7677687697707717727731 unmodified line775776777778779780781782783784785786787788789790791792482 unmodified lines}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 whilethe Python package is later replaced by pip. Querying ``--help`` at runtimeprevents unsupported options such as ``--delete_bad_res`` from being passedto 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_versionversion_text = package_version("meeko")except Exception:passdef 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 = Nonecapabilities = {"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 capabilitiesdef 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 commanddef 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 uniquedef 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 theinstalled CLI advertises a bad-residue tolerance option, one controlledretry is made with that exact supported option. Open Babel is not used tocreate receptor PDBQT because that can generate empty or ligand-style files."""work_dir.mkdir(parents=True, exist_ok=True)suffix = protein_file.suffix.lower()29 unmodified linesmeeko = 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 = Noneif 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 = candidateexcept 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"] = validationattempt_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)5 unmodified lines"cleaning_stats": clean_stats,"cleaned_atom_count": cleaned_atom_count,"protonation": protonation_info,"meeko_runtime": capabilities,"attempts": attempt_reports,},indent=2,1 unmodified lineencoding="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()
qsar_core_streamlit.py+224-60