Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files1234514 unmodified lines2021222324252631 unmodified lines58596061626364656667686970717273749 unmodified lines848586878889909192939495969798991001011021031041051061071081091107 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515616 unmodified lines1731741751761771781791 unmodified line18118218318418518618718818919019119219319419519619719819913 unmodified lines2132142152162172182192202212222232242 unmodified lines2272282292302312322332342352362372382392402412421 unmodified line24424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933055 unmodified lines3863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835849 unmodified lines59459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563617 unmodified lines6546556566576586596606616626638 unmodified lines6726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807811 unmodified line7837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049 unmodified lines914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581 unmodified line106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182import jsonimport mathimport osimport reimport shutil14 unmodified linesSUPPORTED_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)31 unmodified linesreturn 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:9 unmodified linesdef safe_filename(name: str) -> str:name = Path(name).namename = re.sub(r"[^A-Za-z0-9._-]+", "_", name)return name or "uploaded_file"def 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()7 unmodified linesreturn 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}"save_uploaded_file(ligand_upload, ligand_path)st.session_state["saved_ligand_path"] = str(ligand_path)st.session_state["saved_ligand_name"] = ligand_upload.namedef 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:for line in f:if not (line.startswith("ATOM") or line.startswith("HETATM")):continuetry:atoms.append(16 unmodified linesdef parse_residue_selection(selection_text: str) -> List[Tuple[str, int, Optional[str]]]:selections: List[Tuple[str, int, Optional[str]]] = []if not selection_text.strip():return selections1 unmodified linefor 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))continue13 unmodified linesreturn selectionsdef get_atoms_for_selected_residues(protein_file: Path,selections: List[Tuple[str, int, Optional[str]]]) -> 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:2 unmodified linescontinueif res_name is not None and atom.res_name.upper() != res_name.upper():continuematched_atoms.append(atom)breakreturn matched_atomsdef compute_box_from_atoms(atoms: List[AtomRecord],padding: float = 8.0,min_size: float = 18.0) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]:if not atoms:raise ValueError("No atoms were found for box calculation.")1 unmodified lineys = [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, sizedef compute_blind_docking_box(protein_file: Path,padding: float = 8.0,min_size: float = 20.0) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]:atoms = parse_pdb_like_atoms(protein_file)if not atoms:raise ValueError("No protein atoms were found for blind docking.")return compute_box_from_atoms(atoms, padding=padding, min_size=min_size)def compute_residue_based_box(protein_file: Path,residue_selection_text: str,padding: float = 8.0,min_size: float = 18.0) -> 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:key = (atom.chain_id, atom.res_seq, atom.res_name)if key not in seen:seen.add(key)matched_rows.append({"chain": atom.chain_id, "residue_number": atom.res_seq, "residue_name": atom.res_name})matched_df = pd.DataFrame(sorted(matched_rows, key=lambda x: (x["chain"], x["residue_number"])))return center, size, matched_dfdef 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"}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]:"""More aggressive cleaning to reduce mk_prepare_receptor / RDKit valence failures.Keeps only standard protein ATOM records.Drops waters, altlocs except blank/A, hydrogens, ANISOU, CONECT, TER from input."""stats = {"kept_atoms": 0,"dropped_non_atom": 0,55 unmodified linesfout.write("TER\nEND\n")if stats["kept_atoms"] == 0:raise ValueError("No valid standard protein atoms remained after 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 group_residues_from_pdb(pdb_path: Path) -> Dict[str, List[Tuple[str, int, str]]]:residues_by_chain: Dict[str, List[Tuple[str, int, str]]] = {}seen = set()with open(pdb_path, "r", errors="ignore") as f:for line in f:if not line.startswith("ATOM"):continuechain = line[21].strip() or "A"res_name = line[17:20].strip().upper()try:res_seq = int(line[22:26].strip() or 0)except Exception:continuekey = (chain, res_seq, res_name)if key not in seen:seen.add(key)residues_by_chain.setdefault(chain, []).append(key)return residues_by_chaindef write_filtered_pdb(infile: Path, outfile: Path, keep_chain: Optional[str] = None) -> None:kept = 0with open(infile, "r", errors="ignore") as fin, open(outfile, "w") as fout:for line in fin:if not line.startswith("ATOM"):continuechain = line[21].strip() or "A"if keep_chain and chain != keep_chain:continuefout.write(line)kept += 1fout.write("TER\nEND\n")if kept == 0:raise ValueError("Filtered receptor PDB contains no atoms.")def try_meeko_prepare(input_pdb: Path,work_dir: Path,center: Tuple[float, float, float],size: Tuple[float, float, float],prefix: str,) -> Tuple[bool, Optional[Path], str]:out_base = work_dir / prefixcmd = ["mk_prepare_receptor.py","--read_pdb", str(input_pdb),"-o", str(out_base),"-p","--box_center", str(center[0]), str(center[1]), str(center[2]),"--box_size", str(size[0]), str(size[1]), str(size[2]),"--allow_bad_res",]result = run_cmd(cmd, cwd=str(work_dir))candidates = [work_dir / f"{prefix}.pdbqt",work_dir / f"{prefix}_rigid.pdbqt",]pdbqt_path = next((p for p in candidates if p.exists()), None)if result.returncode == 0 and pdbqt_path is not None:validate_receptor_pdbqt(pdbqt_path)return True, pdbqt_path, (result.stdout or "") + "\n" + (result.stderr or "")return False, None, (result.stdout or "") + "\n" + (result.stderr or "")def prepare_receptor_with_obabel(work_dir: Path, input_pdb: Path) -> Path:"""Fast fallback when mk_prepare_receptor.py fails with RDKit valence errors."""if not ensure_command("obabel"):raise RuntimeError("obabel is required for receptor fallback preparation but was not found.")out_pdbqt = work_dir / "receptor_fallback_obabel.pdbqt"cmd = ["obabel", str(input_pdb), "-O", str(out_pdbqt), "-xr"]result = run_cmd(cmd, cwd=str(work_dir))if result.returncode != 0 or not out_pdbqt.exists():raise RuntimeError("Fallback receptor preparation with Open Babel failed.\n"f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")validate_receptor_pdbqt(out_pdbqt)return out_pdbqtdef prepare_receptor_pdbqt(work_dir: Path,protein_file: Path,center: Tuple[float, float, float],size: Tuple[float, float, float],) -> Tuple[Path, Path, Dict[str, object]]: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, {"strategy": "input_pdbqt","removed_residues": [],}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)# Fast path 1: whole cleaned receptorif ensure_command("mk_prepare_receptor.py"):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","cleaning_stats": clean_stats,"removed_residues": [],}else:log_text = "mk_prepare_receptor.py not found."# Fast path 2: largest chain only (single rescue, no slow residue-by-residue loop)residues_by_chain = group_residues_from_pdb(cleaned_pdb)selected_chain = Noneif residues_by_chain and ensure_command("mk_prepare_receptor.py"):selected_chain = sorted(residues_by_chain.items(), key=lambda x: len(x[1]), reverse=True)[0][0]chain_pdb = work_dir / f"receptor_chain_{selected_chain}.pdb"write_filtered_pdb(cleaned_pdb, chain_pdb, keep_chain=selected_chain)ok, pdbqt_path, chain_log = try_meeko_prepare(chain_pdb, work_dir, center, size, f"receptor_chain_{selected_chain}")if ok:return pdbqt_path, chain_pdb, {"strategy": f"single_chain_{selected_chain}","cleaning_stats": clean_stats,"removed_residues": [],"selected_chain": selected_chain,}log_text += "\n\nLargest-chain attempt log:\n" + chain_log# Fast fallback 3: Open Babel conversiontry:fallback_pdbqt = prepare_receptor_with_obabel(work_dir, cleaned_pdb)return fallback_pdbqt, cleaned_pdb, {"strategy": "obabel_fallback","cleaning_stats": clean_stats,"removed_residues": [],"selected_chain": selected_chain,"note": "Used Open Babel fallback because mk_prepare_receptor.py failed or was unavailable.",}except Exception as e:raise RuntimeError("Receptor preparation failed after fast attempts.\n\n"f"mk_prepare_receptor / chain attempt log:\n{log_text}\n\n"f"Cleaning stats: {json.dumps(clean_stats, indent=2)}\n\n"f"Fallback Open Babel error:\n{str(e)}")def 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=300)return mol, "smiles"assert ligand_file is not Nonesuffix = ligand_file.suffix.lower()if suffix == ".sdf":9 unmodified linesraise 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=300)return mol, suffix.lstrip(".")def write_ligand_sdf(mol: Chem.Mol, sdf_path: Path) -> None:writer = Chem.SDWriter(str(sdf_path))writer.write(mol)writer.close()def prepare_ligand_pdbqt(work_dir: Path, ligand_file: Optional[Path], smiles_text: str) -> Path:if ligand_file is not None and ligand_file.suffix.lower() == ".pdbqt":dst = work_dir / "ligand_input.pdbqt"shutil.copy2(ligand_file, dst)validate_ligand_pdbqt(dst)return dstif not ensure_command("obabel"):raise RuntimeError("obabel is required for ligand preparation but was not found.")mol, _ = ligand_mol_from_input(ligand_file, smiles_text)sdf_path = work_dir / "ligand_prepared.sdf"write_ligand_sdf(mol, sdf_path)out_pdbqt = work_dir / "ligand.pdbqt"result = run_cmd(["obabel", str(sdf_path), "-O", str(out_pdbqt), "-xh"], cwd=str(work_dir))if result.returncode != 0 or not out_pdbqt.exists():raise RuntimeError(f"Ligand preparation failed.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")validate_ligand_pdbqt(out_pdbqt)return out_pdbqt17 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"):8 unmodified lineslines.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) -> 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:"""Combine receptor and docked ligand into one LigPlus/LigPlot-readable PDB file.This function preserves receptor coordinates and ligand docked coordinates whilerebuilding the output lines with strict PDB column alignment. The ligand is writtenas HETATM with residue name LIG, chain Z, and residue number 1 so that LigPlus cancorrectly identify it as a ligand."""serial = 1ligand_resname = (ligand_resname or "LIG")[:3].upper()ligand_chain = (ligand_chain or "Z")[:1]def safe_float(field: str, default: float = 0.0) -> float:try:return float(field.strip())except Exception:return defaultdef safe_int(field: str, default: int = 1) -> int:try:return int(field.strip())except Exception:return defaultdef format_atom_name(atom_name: str, element: str) -> str:"""Format atom name into the 4-character PDB atom-name field.This keeps LigPlus/RasMol/PyMOL recognition stable."""atom_name = (atom_name or "C").strip()[:4]element = (element or infer_element_from_atom_name(atom_name) or "C").strip()if len(element) == 1 and len(atom_name) < 4:return f" {atom_name:<3}"return f"{atom_name:<4}"def write_pdb_line(record: str,atom_serial: int,atom_name: str,res_name: str,chain_id: str,res_seq: int,x: float,y: float,z: float,occupancy: float,temp_factor: float,element: str,) -> str:record = record[:6].ljust(6)element = (element or infer_element_from_atom_name(atom_name) or "C").strip()[:2]atom_field = format_atom_name(atom_name, element)return (f"{record}{atom_serial:5d} "f"{atom_field}"f" "f"{res_name[:3].upper():>3} "f"{chain_id[:1] or 'A'}"f"{res_seq:4d}"f" "f"{x:8.3f}{y:8.3f}{z:8.3f}"f"{occupancy:6.2f}{temp_factor:6.2f}"f" "f"{element:>2}")with open(complex_pdb, "w") as out:# Rebuild receptor ATOM records with valid serial numbers and stable columns.with open(receptor_pdb, "r", errors="ignore") as fin:for line in fin:if not line.startswith("ATOM"):continueif len(line) < 80:line = line.rstrip("\n").ljust(80)atom_name = line[12:16].strip()res_name = line[17:20].strip() or "UNK"chain_id = line[21].strip() or "A"1 unmodified linex = safe_float(line[30:38])y = safe_float(line[38:46])z = safe_float(line[46:54])occupancy = safe_float(line[54:60], 1.00)temp_factor = safe_float(line[60:66], 0.00)element = line[76:78].strip() or infer_element_from_atom_name(atom_name)out.write(write_pdb_line("ATOM",serial,atom_name,res_name,chain_id,res_seq,x,y,z,occupancy,temp_factor,element,)+ "\n")serial += 1out.write("TER\n")# Rebuild ligand as one HETATM residue. This prevents the common LigPlus# problem where LIG is shifted into the wrong PDB columns and appears as no ligand.ligand_resseq = 1ligand_atom_index = 1with open(ligand_pdb, "r", errors="ignore") as fin:for line in fin:if not line.startswith(("ATOM", "HETATM")):continueif len(line) < 80:line = line.rstrip("\n").ljust(80)original_atom_name = line[12:16].strip()element = line[76:78].strip() or infer_element_from_atom_name(original_atom_name)if not element:element = "C"# Give each ligand atom a safe unique atom name if Open Babel produced# blank/duplicated names. Coordinates are not altered.base_element = element.strip().upper()atom_name = original_atom_name or f"{base_element}{ligand_atom_index}"atom_name = atom_name[:4]x = safe_float(line[30:38])y = safe_float(line[38:46])z = safe_float(line[46:54])out.write(write_pdb_line("HETATM",serial,atom_name,ligand_resname,ligand_chain,ligand_resseq,x,y,z,1.00,0.00,element,)+ "\n")serial += 1ligand_atom_index += 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 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],smiles_text: str,center: Tuple[float, float, float],size: Tuple[float, float, float],exhaustiveness: int,num_modes: int,) -> Dict[str, Path]:with tempfile.TemporaryDirectory(prefix="dockapp_job_") as tmpdir:work_dir = Path(tmpdir)receptor_pdbqt, receptor_source, receptor_prep_info = 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"cmd = ["vina",9 unmodified lines"--num_modes", str(num_modes),"--out", str(docked_pdbqt),]result = run_cmd(cmd, cwd=str(work_dir))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_stdout((result.stdout or "") + "\n" + (result.stderr or ""))if scores_df.empty:raise RuntimeError("Docking completed, but no score table could be parsed from Vina output.")scores_csv = work_dir / "docking_scores.csv"scores_df.to_csv(scores_csv, index=False)best_pose_pdbqt = work_dir / "best_pose_model1.pdbqt"split_first_model_pdbqt(docked_pdbqt, best_pose_pdbqt)receptor_pdb = work_dir / "receptor_for_complex.pdb"best_pose_pdb = work_dir / "best_ligand_pose.pdb"best_complex_pdb = work_dir / "best_protein_ligand_complex.pdb"convert_structure_to_pdb(receptor_source, receptor_pdb)convert_structure_to_pdb(best_pose_pdbqt, best_pose_pdb)combine_protein_and_ligand_pdb(receptor_pdb, best_pose_pdb, best_complex_pdb)summary_json = work_dir / "summary.json"summary_payload = {"protein_file": protein_file.name,"ligand_file": ligand_file.name if ligand_file else "SMILES input","grid_center": {"x": center[0], "y": center[1], "z": center[2]},"grid_size": {"x": size[0], "y": size[1], "z": size[2]},"best_affinity_kcal_per_mol": float(scores_df.iloc[0]["affinity_kcal_per_mol"]),"receptor_preparation": receptor_prep_info,}summary_json.write_text(json.dumps(summary_payload, indent=2))export_dir = get_export_dir()out_map = {"scores_csv": export_dir / "docking_scores.csv","best_pose_pdbqt": export_dir / "best_pose_model1.pdbqt","best_pose_pdb": export_dir / "best_ligand_pose.pdb","best_complex_pdb": export_dir / "best_protein_ligand_complex.pdb","summary_json": export_dir / "summary.json",}shutil.copy2(scores_csv, out_map["scores_csv"])shutil.copy2(best_pose_pdbqt, out_map["best_pose_pdbqt"])shutil.copy2(best_pose_pdb, out_map["best_pose_pdb"])shutil.copy2(best_complex_pdb, out_map["best_complex_pdb"])shutil.copy2(summary_json, out_map["summary_json"])zip_path = export_dir / "docking_results_bundle.zip"make_zip(zip_path, list(out_map.values()))out_map["zip"] = zip_pathreturn 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("Fast docking workflow with compact outputs and receptor fallback handling.")with st.sidebar:st.header("Run settings")exhaustiveness = st.slider("Exhaustiveness", 4, 24, 8, 2)num_modes = st.slider("Number of poses", 1, 10, 5, 1)if st.button("Clear all inputs and results"):reset_all()missing_cmds = [cmd for cmd in ["vina", "obabel"] 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.")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 box definition")docking_mode = st.radio("Choose docking mode",["Residue-based docking", "Blind docking", "Manual box coordinates"],1 unmodified line)residue_selection_text = ""center_x = center_y = center_z = 0.0size_x = size_y = size_z = 20.0padding = 8.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("Padding around whole protein (Å)", 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:if 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, _ = 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"] = {"files": {k: str(v) for k, v in outputs.items()},"center": center,"size": size,"mode": docking_mode,}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"])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.subheader("Receptor preparation summary")st.json(summary.get("receptor_preparation", {}))st.subheader("Docking scores")st.dataframe(scores_df, use_container_width=True)d1, d2, d3 = st.columns(3)with d1: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 d2: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 d3:with open(outputs["zip"], "rb") as f:st.download_button("Download results ZIP",f.read(),file_name="docking_results_bundle.zip",mime="application/zip",)if __name__ == "__main__":main()123456714 unmodified lines2223242526272831 unmodified lines606162636465666768697071727374757677787980818283848586879 unmodified lines9798991001011021031041051061071081091101117 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514616 unmodified lines1631641651661671681691 unmodified line17117217317417517617717817918018118218318418513 unmodified lines1992002012022032042052062072 unmodified lines2102112122132142152162172182192202211 unmodified line22322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327455 unmodified lines3303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254269 unmodified lines43643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651717 unmodified lines5355365375385395405415425435445458 unmodified lines5545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226231 unmodified line6256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966979 unmodified lines7077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478481 unmodified line850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032#!/usr/bin/env python3# -*- coding: utf-8 -*-import jsonimport osimport reimport shutil14 unmodified linesSUPPORTED_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)31 unmodified linesreturn shutil.which(cmd) is not Nonedef run_cmd(cmd: List[str], cwd: Optional[str] = None, timeout: int = 600):try:return subprocess.run(cmd,cwd=cwd,text=True,capture_output=True,check=False,timeout=timeout,)except subprocess.TimeoutExpired as e:return subprocess.CompletedProcess(cmd,returncode=124,stdout=e.stdout or "",stderr=f"TIMEOUT after {timeout} seconds")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:9 unmodified linesdef safe_filename(name: str) -> str:name = Path(str(name)).namename = 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()7 unmodified linesreturn out_pathdef 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")):continuetry:atoms.append(16 unmodified linesdef parse_residue_selection(selection_text: str) -> List[Tuple[str, int, Optional[str]]]:selections = []if not selection_text.strip():return selections1 unmodified linefor 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))continue13 unmodified linesreturn selectionsdef 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:2 unmodified linescontinueif res_name is not None and atom.res_name.upper() != res_name.upper():continuematched.append(atom)breakreturn matcheddef compute_box_from_atoms(atoms, padding=8.0, min_size=18.0):if not atoms:raise ValueError("No atoms were found for box calculation.")1 unmodified lineys = [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, sizedef 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) -> str:atom_name = (atom_name or "").strip()letters = "".join(ch for ch in atom_name if ch.isalpha()).upper()if not letters:return ""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,55 unmodified linesfout.write("TER\nEND\n")if stats["kept_atoms"] == 0:raise ValueError("No valid protein atoms remained after cleaning.")return statsdef validate_receptor_pdbqt(pdbqt_path: Path):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 tags: {', '.join(bad_tags)}")if "ATOM" not in text and "HETATM" not in text:raise RuntimeError("Receptor PDBQT appears empty.")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 prepare_receptor_once(work_dir: Path, protein_file: Path, center, size, timeout=600):suffix = protein_file.suffix.lower()if suffix == ".pdbqt":receptor_pdbqt = work_dir / "prepared_receptor.pdbqt"receptor_pdb = work_dir / "receptor_source.pdbqt"shutil.copy2(protein_file, receptor_pdbqt)shutil.copy2(protein_file, receptor_pdb)validate_receptor_pdbqt(receptor_pdbqt)return receptor_pdbqt, receptor_pdb, {"strategy": "input_pdbqt"}cleaned_pdb = work_dir / "receptor_cleaned.pdb"clean_stats = strict_clean_receptor_pdb(protein_file, cleaned_pdb)receptor_pdbqt = work_dir / "prepared_receptor.pdbqt"if ensure_command("mk_prepare_receptor.py"):out_base = work_dir / "prepared_receptor"cmd = ["mk_prepare_receptor.py","--read_pdb", str(cleaned_pdb),"-o", str(out_base),"-p","--box_center", str(center[0]), str(center[1]), str(center[2]),"--box_size", str(size[0]), str(size[1]), str(size[2]),"--allow_bad_res",]result = run_cmd(cmd, cwd=str(work_dir), timeout=timeout)candidates = [work_dir / "prepared_receptor.pdbqt",work_dir / "prepared_receptor_rigid.pdbqt",]made = next((p for p in candidates if p.exists()), None)if result.returncode == 0 and made:shutil.copy2(made, receptor_pdbqt)validate_receptor_pdbqt(receptor_pdbqt)return receptor_pdbqt, cleaned_pdb, {"strategy": "meeko_once","cleaning_stats": clean_stats,"stdout": result.stdout[-1000:],"stderr": result.stderr[-1000:],}if not ensure_command("obabel"):raise RuntimeError("Receptor preparation failed and obabel fallback is not available.")result = run_cmd(["obabel", str(cleaned_pdb), "-O", str(receptor_pdbqt), "-xr"],cwd=str(work_dir),timeout=timeout,)if result.returncode != 0 or not receptor_pdbqt.exists():raise RuntimeError("Receptor preparation failed.\n"f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")validate_receptor_pdbqt(receptor_pdbqt)return receptor_pdbqt, cleaned_pdb, {"strategy": "obabel_fallback_once","cleaning_stats": clean_stats,"stdout": result.stdout[-1000:],"stderr": result.stderr[-1000:],}def ligand_mol_from_input(ligand_file: Path):suffix = ligand_file.suffix.lower()if suffix == ".sdf":9 unmodified linesraise 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 moldef prepare_ligand_pdbqt(work_dir: Path, ligand_file: Path, timeout=300):if ligand_file.suffix.lower() == ".pdbqt":dst = work_dir / "ligand.pdbqt"shutil.copy2(ligand_file, dst)validate_ligand_pdbqt(dst)return dstif not ensure_command("obabel"):raise RuntimeError("obabel is required for ligand preparation.")mol = ligand_mol_from_input(ligand_file)sdf_path = work_dir / "ligand_prepared.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("Ligand preparation failed.\n"f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")validate_ligand_pdbqt(out_pdbqt)return out_pdbqtdef 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_pdbqt17 unmodified linesreturn pd.DataFrame(rows)def split_first_model_pdbqt(pdbqt_path: Path, out_path: Path):lines = []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")def convert_structure_to_pdb(input_path: Path, output_path: Path, timeout=300):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 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_pathdef combine_protein_and_ligand_pdb(receptor_pdb: Path, ligand_pdb: Path, complex_pdb: Path):serial = 1def safe_float(field, default=0.0):try:return float(field.strip())except Exception:return defaultdef safe_int(field, default=1):try:return int(field.strip())except Exception:return defaultdef write_line(record, atom_serial, atom_name, res_name, chain_id, res_seq, x, y, z, occ, bfac, element):atom_name = (atom_name or element or "C")[:4]element = (element or infer_element_from_atom_name(atom_name) or "C")[:2]return (f"{record:<6}{atom_serial:5d} "f"{atom_name:<4} "f"{res_name[:3].upper():>3} "f"{chain_id[:1] or 'A'}"f"{res_seq:4d}"f" "f"{x:8.3f}{y:8.3f}{z:8.3f}"f"{occ:6.2f}{bfac:6.2f}"f" {element:>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"):continueline = line.rstrip("\n").ljust(80)atom_name = line[12:16].strip()res_name = line[17:20].strip() or "UNK"chain_id = line[21].strip() or "A"1 unmodified linex = 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() or infer_element_from_atom_name(atom_name)out.write(write_line("ATOM", serial, atom_name, res_name, chain_id, res_seq, x, y, z, occ, bfac, element) + "\n")serial += 1out.write("TER\n")ligand_index = 1with open(ligand_pdb, "r", errors="ignore") as fin:for line in fin:if not line.startswith(("ATOM", "HETATM")):continueline = line.rstrip("\n").ljust(80)atom_name = line[12:16].strip()element = line[76:78].strip() or infer_element_from_atom_name(atom_name) or "C"if not atom_name:atom_name = f"{element}{ligand_index}"[:4]x = safe_float(line[30:38])y = safe_float(line[38:46])z = safe_float(line[46:54])out.write(write_line("HETATM", serial, atom_name, "LIG", "Z", 1, x, y, z, 1.00, 0.00, element) + "\n")serial += 1ligand_index += 1out.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,):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",9 unmodified lines"--num_modes", str(num_modes),"--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": "","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": "","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)summary = {"ligand": ligand_name,"status": "SUCCESS","best_affinity_kcal_per_mol": float(scores_df.iloc[0]["affinity_kcal_per_mol"]),"grid_center": {"x": center[0], "y": center[1], "z": center[2]},"grid_size": {"x": size[0], "y": size[1], "z": size[2]},}(ligand_dir / "summary.json").write_text(json.dumps(summary, indent=2))return {"ligand": ligand_name,"status": "SUCCESS","best_affinity_kcal_per_mol": float(scores_df.iloc[0]["affinity_kcal_per_mol"]),"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": "","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:continueif "," 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}", lineligands.append({"name": safe_filename(name), "smiles": smiles})return ligandsdef main():st.set_page_config(page_title="Batch Protein-Ligand Docking Tool", layout="wide")init_state()st.title("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", 4, 24, 6, 2)num_modes = st.slider("Number of poses", 1, 10, 3, 1)prep_timeout = st.number_input("Preparation timeout per step (seconds)", min_value=60, max_value=1800, value=300, step=60)vina_timeout = st.number_input("Vina timeout per ligand (seconds)", min_value=120, max_value=7200, value=900, step=120)st.warning("For many ligands, use exhaustiveness 4–6 and poses 3.")if st.button("Clear all inputs and results"):reset_all()missing_cmds = [cmd for cmd in ["vina", "obabel"] if not ensure_command(cmd)]if missing_cmds:st.error("Missing required command(s): " + ", ".join(missing_cmds))st.stop()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,)st.subheader("Step 2: Docking box definition")docking_mode = st.radio("Choose docking mode",["Residue-based docking", "Blind docking", "Manual box coordinates"],1 unmodified line)residue_selection_text = ""padding = 8.0center = (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)elif docking_mode == "Residue-based docking":center, size = compute_residue_based_box(protein_path, residue_selection_text, padding=padding, min_size=18.0)st.info(f"Docking box center: {center}; size: {size}")batch_dir = export_dir / "batch_docking_results"batch_dir.mkdir(parents=True, exist_ok=True)with tempfile.TemporaryDirectory(prefix="batch_receptor_") as tmp:receptor_work = Path(tmp)with st.spinner("Preparing receptor once..."):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"shutil.copy2(receptor_pdbqt, fixed_receptor_pdbqt)convert_structure_to_pdb(receptor_source, fixed_receptor_source, timeout=prep_timeout)(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])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,)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))outputs = st.session_state.get("run_outputs")if outputs:st.subheader("Batch docking summary")df = pd.DataFrame(outputs["summary_df"])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()))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()
qsar_core_streamlit.py+495-645