Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files123456763 unmodified lines717273747576374 unmodified lines4514524534544554565 unmodified lines4624634644654664674686 unmodified lines47547647747847948048137 unmodified lines51952052152252352452552652752852953053153253353453553612 unmodified lines5495505515525535545555565575585595605615625635645651 unmodified line56756856957057157257357457557657757821 unmodified lines600601602603604605import jsonimport mathimport osimport re # ← ADD THIS LINEimport shutilimport subprocessimport tempfile63 unmodified linesreturn atomsdef write_residue_subset_pdb(infile: Path, residue_keys: List[Tuple[str, int, str]], outfile: Path) -> None:wanted = {(chain, seq, res) for chain, seq, res in residue_keys}with open(infile, "r", errors="ignore") as fin, open(outfile, "w") as fout:374 unmodified lines"protein_name","ligand_name","run_outputs",]:if key in st.session_state:del st.session_state[key]5 unmodified linesinit_state()st.title("Protein-Ligand Docking Tool")st.caption("Upload a protein, upload a ligand or paste a SMILES string, define the grid box, then run AutoDock Vina.")with st.sidebar:st.header("Run settings")6 unmodified linesmissing_cmds = [cmd for cmd in ["vina", "obabel", "mk_prepare_receptor.py"] if not ensure_command(cmd)]if missing_cmds:st.error("Missing container tools: " + ", ".join(missing_cmds) +". Fix the Dockerfile first, rebuild the Space, then test upload again.")37 unmodified lines)with col2:st.subheader("Docking box")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")st.info("The docking box is defined by the center coordinates and box size used by AutoDock Vina.")run_clicked = st.button("Run docking", type="primary", disabled=bool(missing_cmds))12 unmodified linesif ligand_upload is not None:ligand_path = save_uploaded_file(ligand_upload, tmpdir / ligand_upload.name)outputs = run_docking(protein_file=protein_path,ligand_file=ligand_path,smiles_text=smiles_text,center=(center_x, center_y, center_z),size=(size_x, size_y, size_z),exhaustiveness=exhaustiveness,num_modes=num_modes,)st.session_state["run_outputs"] = {k: str(v) for k, v in outputs.items()}st.success("Docking completed successfully.")except Exception as e:1 unmodified lineoutputs_raw = st.session_state.get("run_outputs")if outputs_raw:outputs = {k: Path(v) for k, v in outputs_raw.items()}try:scores_df = pd.read_csv(outputs["scores_csv"])residues_df = pd.read_csv(outputs["residues_csv"])summary = json.loads(outputs["summary_json"].read_text())m1, m2 = st.columns(2)with m1:st.metric("Best binding affinity (kcal/mol)", summary.get("best_affinity_kcal_per_mol"))21 unmodified linesst.download_button("Download active-site residues structure PDB", f.read(), file_name="active_site_residues.pdb")with open(outputs["zip"], "rb") as f:st.download_button("Download complete ZIP bundle", f.read(), file_name="docking_results_bundle.zip", mime="application/zip")except Exception as e:st.error(f"Saved results could not be displayed: {e}")12345663 unmodified lines707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232374 unmodified lines6076086096106116126135 unmodified lines6196206216226236246256 unmodified lines63263363463563663763837 unmodified lines67667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272312 unmodified lines7367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757761 unmodified line77877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181221 unmodified lines834835836837838839840import jsonimport mathimport reimport shutilimport subprocessimport tempfile63 unmodified linesreturn atomsdef parse_residue_selection(selection_text: str) -> List[Tuple[str, int, Optional[str]]]:"""Accepted examples:A:45A:45,46,47A:45-50A:LYS45A:LYS45,ASP46,GLU47A:LYS45;B:TYR120"""selections: List[Tuple[str, int, Optional[str]]] = []if not selection_text.strip():return selectionsblocks = [b.strip() for b in selection_text.split(";") if b.strip()]for block in blocks:if ":" not in block:raise ValueError(f"Invalid residue block '{block}'. Use formats like A:45, A:LYS45, or A:45-50.")chain, spec = block.split(":", 1)chain = chain.strip()spec = spec.strip()if not chain:raise ValueError(f"Missing chain in block '{block}'.")items = [x.strip() for x in spec.split(",") if x.strip()]for item in items:m_range_num = re.fullmatch(r"(\d+)\s*-\s*(\d+)", item)if m_range_num:start = int(m_range_num.group(1))end = int(m_range_num.group(2))if end < start:raise ValueError(f"Invalid range '{item}' in block '{block}'.")for rnum in range(start, end + 1):selections.append((chain, rnum, None))continuem_named = re.fullmatch(r"([A-Za-z]{3})(\d+)", item)if m_named:res_name = m_named.group(1).upper()res_num = int(m_named.group(2))selections.append((chain, res_num, res_name))continuem_num = re.fullmatch(r"(\d+)", item)if m_num:selections.append((chain, int(m_num.group(1)), None))continueraise ValueError(f"Could not parse residue item '{item}'. Use A:45, A:45-50, or A:LYS45.")return 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:continueif atom.res_seq != res_num:continueif 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.")xs = [a.x for a in atoms]ys = [a.y for a in atoms]zs = [a.z for a in atoms]xmin, xmax = min(xs), max(xs)ymin, ymax = min(ys), max(ys)zmin, zmax = min(zs), max(zs)center = (round((xmin + xmax) / 2.0, 3),round((ymin + ymax) / 2.0, 3),round((zmin + zmax) / 2.0, 3),)size = (round(max((xmax - xmin) + 2 * padding, min_size), 3),round(max((ymax - ymin) + 2 * padding, min_size), 3),round(max((zmax - zmin) + 2 * padding, min_size), 3),)return center, 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, e.g. A:LYS45,ASP46 or A:45-50.")selected_atoms = get_atoms_for_selected_residues(protein_file, selections)if not selected_atoms:raise ValueError("None of the specified residues were found in the uploaded protein file.")center, size = compute_box_from_atoms(selected_atoms, padding=padding, min_size=min_size)matched_rows = []seen = set()for atom in selected_atoms: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 write_residue_subset_pdb(infile: Path, residue_keys: List[Tuple[str, int, str]], outfile: Path) -> None:wanted = {(chain, seq, res) for chain, seq, res in residue_keys}with open(infile, "r", errors="ignore") as fin, open(outfile, "w") as fout:374 unmodified lines"protein_name","ligand_name","run_outputs","residue_selection_text",]:if key in st.session_state:del st.session_state[key]5 unmodified linesinit_state()st.title("Protein-Ligand Docking Tool")st.caption("Upload a protein, upload a ligand or paste a SMILES string, then run blind, residue-based, or manual docking.")with st.sidebar:st.header("Run settings")6 unmodified linesmissing_cmds = [cmd for cmd in ["vina", "obabel", "mk_prepare_receptor.py"] if not ensure_command(cmd)]if missing_cmds:st.error("Missing container tools: " + ", ".join(missing_cmds) +". Fix the Dockerfile first, rebuild the Space, then test upload again.")37 unmodified lines)with col2:st.subheader("Docking mode and box definition")docking_mode = st.radio("Choose docking mode",["Residue-based docking", "Blind docking", "Manual box coordinates"],index=0,)residue_selection_text = ""padding = 8.0center_x = center_y = center_z = 0.0size_x = size_y = size_z = 20.0if docking_mode == "Residue-based docking":st.markdown("Specify residues using chain and residue identifiers.")st.code("Examples:\nA:LYS45,ASP46,GLU47\nA:45,46,47\nA:45-50\nA:LYS45;B:TYR120",language="text",)residue_selection_text = st.text_area("Residues and chains",placeholder="A:LYS45,ASP46,GLU47",key="residue_selection_text",)padding = st.number_input("Padding around selected residues (Å)", min_value=2.0, value=8.0, step=1.0)elif docking_mode == "Blind docking":st.info("The docking box will be generated automatically from the whole protein.")padding = st.number_input("Blind docking padding (Å)", min_value=2.0, value=8.0, step=1.0)else:c1, c2, c3 = st.columns(3)center_x = c1.number_input("Center X", value=0.0, format="%.3f")center_y = c2.number_input("Center Y", value=0.0, format="%.3f")center_z = c3.number_input("Center Z", value=0.0, format="%.3f")s1, s2, s3 = st.columns(3)size_x = s1.number_input("Size X", value=20.0, min_value=5.0, format="%.3f")size_y = s2.number_input("Size Y", value=20.0, min_value=5.0, format="%.3f")size_z = s3.number_input("Size Z", value=20.0, min_value=5.0, format="%.3f")st.info("Manual docking uses explicit center coordinates and box sizes.")run_clicked = st.button("Run docking", type="primary", disabled=bool(missing_cmds))12 unmodified linesif ligand_upload is not None:ligand_path = save_uploaded_file(ligand_upload, tmpdir / ligand_upload.name)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)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,"matched_residues": residue_match_df.to_dict(orient="records") if residue_match_df is not None else None,}st.success("Docking completed successfully.")except Exception as e:1 unmodified lineoutputs_raw = st.session_state.get("run_outputs")if outputs_raw:try:outputs = {k: Path(v) for k, v in outputs_raw["files"].items()}center = tuple(outputs_raw["center"])size = tuple(outputs_raw["size"])docking_mode = outputs_raw["mode"]matched_residues = outputs_raw.get("matched_residues")scores_df = pd.read_csv(outputs["scores_csv"])residues_df = pd.read_csv(outputs["residues_csv"])summary = json.loads(outputs["summary_json"].read_text())st.subheader("Computed docking box")b1, b2, b3 = st.columns(3)with b1:st.metric("Center X", center[0])st.metric("Size X", size[0])with b2:st.metric("Center Y", center[1])st.metric("Size Y", size[1])with b3:st.metric("Center Z", center[2])st.metric("Size Z", size[2])st.info(f"Docking mode used: {docking_mode}")if docking_mode == "Residue-based docking" and matched_residues:st.subheader("Matched residues used to define the box")st.dataframe(pd.DataFrame(matched_residues), use_container_width=True)m1, m2 = st.columns(2)with m1:st.metric("Best binding affinity (kcal/mol)", summary.get("best_affinity_kcal_per_mol"))21 unmodified linesst.download_button("Download active-site residues structure PDB", f.read(), file_name="active_site_residues.pdb")with open(outputs["zip"], "rb") as f:st.download_button("Download complete ZIP bundle", f.read(), file_name="docking_results_bundle.zip", mime="application/zip")except Exception as e:st.error(f"Saved results could not be displayed: {e}")
qsar_core_streamlit.py+253-18