Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files692 unmodified lines6936946956966976981 unmodified line70070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874 unmodified lines82382482582682782882983083183283311 unmodified lines845846847848849850851852853854855856857858186 unmodified lines10451046104710481049105010511052105310541055692 unmodified linesreturn output_pathdef combine_protein_and_ligand_pdb(receptor_pdb: Path,ligand_pdb: Path,1 unmodified lineligand_resname: str = "LIG",ligand_chain: str = "Z",) -> None:serial = 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"atom_name_clean = line[12:16].strip()element = line[76:78].strip() if len(line) >= 78 else ""if not element:element = infer_element_from_atom_name(atom_name_clean)new_line = (f"HETATM{serial:5d} {atom_name:<4}{ligand_resname:>3} {ligand_chain}"f"{1: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:74 unmodified linesreceptor_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 = {11 unmodified lines"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"186 unmodified lines)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",)692 unmodified lines6936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337341 unmodified line73673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685774 unmodified lines93293393493593693793893994094194294394494594694794894995011 unmodified lines962963964965966967968969970971972973974975976977978979186 unmodified lines11661167116811691170117111721173117411751176692 unmodified linesreturn output_pathdef convert_ligand_pose_to_ligplot_pdb(input_path: Path, output_path: Path) -> Path:"""Converts the best Vina ligand pose to a LigPlot+-friendly PDB.LigPlot+ commonly fails with docking-derived complexes when the ligand hasno bond connectivity. This Open Babel conversion removes hydrogens andwrites ligand CONECT records where possible."""if not ensure_command("obabel"):raise RuntimeError("obabel is required to create a LigPlot+-ready ligand PDB.")result = run_cmd(["obabel", str(input_path), "-O", str(output_path), "-d"])if result.returncode != 0 or not output_path.exists() or output_path.stat().st_size == 0:raise RuntimeError("Failed to create LigPlot+-ready ligand PDB.\n"f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")text = output_path.read_text(errors="ignore")if "HETATM" not in text and "ATOM" not in text:raise RuntimeError("LigPlot+-ready ligand PDB contains no atom records.")return output_pathdef _is_hydrogen_pdb_line(line: str) -> bool:line = line.rstrip("\n")if len(line) < 80:line = line.ljust(80)atom_name = line[12:16].strip()element = line[76:78].strip()if not element:element = infer_element_from_atom_name(atom_name)return element.upper() == "H" or atom_name.upper().startswith("H")def combine_protein_and_ligand_pdb(receptor_pdb: Path,ligand_pdb: Path,1 unmodified lineligand_resname: str = "LIG",ligand_chain: str = "Z",) -> None:"""Writes a LigPlot+-compatible protein-ligand complex.Key fixes:1. Protein is written as ATOM records only.2. Ligand is written as HETATM with a single 3-letter residue name.3. Ligand hydrogens are removed.4. Ligand CONECT records are preserved and serial numbers are remapped.The CONECT records are the most important fix for the LigPlot+ error:"CORA file empty or not in correct format"."""serial = 1ligand_serial_map: Dict[int, int] = {}ligand_conect_lines: List[str] = []with open(complex_pdb, "w") as out:# Write receptor atomswith open(receptor_pdb, "r", errors="ignore") as fin:for line in fin:if not line.startswith("ATOM"):continueline = line.rstrip("\n")if len(line) < 80:line = line.ljust(80)# Normalize atom serial while keeping standard receptor fieldsnew_line = f"ATOM {serial:5d}{line[11:80]}"out.write(new_line.rstrip() + "\n")serial += 1out.write("TER\n")# Write ligand atoms and remember old-to-new serial mappingwith open(ligand_pdb, "r", errors="ignore") as fin:for line in fin:if line.startswith("CONECT"):ligand_conect_lines.append(line.rstrip("\n"))continueif not line.startswith(("ATOM", "HETATM")):continueif _is_hydrogen_pdb_line(line):continueraw = line.rstrip("\n")if len(raw) < 80:raw = raw.ljust(80)try:old_serial = int(raw[6:11].strip())except Exception:old_serial = serialatom_name = raw[12:16].strip()x = raw[30:38]y = raw[38:46]z = raw[46:54]occ = raw[54:60] if len(raw) >= 60 else " 1.00"bfac = raw[60:66] if len(raw) >= 66 else " 0.00"element = raw[76:78].strip()if not element:element = infer_element_from_atom_name(atom_name)# PDB atom-name alignment suitable for LigPlot+atom_field = f"{atom_name:<4}"[:4]new_line = (f"HETATM{serial:5d} {atom_field}{ligand_resname:>3} {ligand_chain}"f"{1:4d} {x}{y}{z}{occ}{bfac} {element:>2}")out.write(new_line.rstrip() + "\n")ligand_serial_map[old_serial] = serialserial += 1# Preserve ligand bond connectivity after serial-number remappingwrote_conect = 0for conect in ligand_conect_lines:parts = conect.split()if len(parts) < 2:continuetry:old_from = int(parts[1])except Exception:continueif old_from not in ligand_serial_map:continuenew_from = ligand_serial_map[old_from]new_to = []for token in parts[2:]:try:old_to = int(token)except Exception:continueif old_to in ligand_serial_map:new_to.append(ligand_serial_map[old_to])if new_to:out.write(f"CONECT{new_from:5d}" + "".join(f"{x:5d}" for x in new_to) + "\n")wrote_conect += 1out.write("END\n")if not ligand_serial_map:raise RuntimeError("No ligand heavy atoms were written to the complex PDB.")# LigPlot+ needs ligand connectivity. Warn by side effect through exception only if none exist.# If your Open Babel build cannot write CONECT, update Open Babel or use SDF/MOL2 as ligand input.if wrote_conect == 0:raise RuntimeError("The LigPlot+-ready complex was created but no ligand CONECT records were written. ""LigPlot+ may still fail. Use a ligand file with bond information, preferably SDF or MOL2.")def make_zip(zip_path: Path, files: List[Path]) -> None:with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:74 unmodified linesreceptor_pdb = work_dir / "receptor_for_complex.pdb"best_pose_pdb = work_dir / "best_ligand_pose.pdb"best_pose_ligplot_pdb = work_dir / "best_ligand_pose_ligplot_ready.pdb"best_complex_pdb = work_dir / "best_protein_ligand_complex.pdb"best_complex_ligplot_pdb = work_dir / "best_protein_ligand_complex_LigPlot_ready.pdb"convert_structure_to_pdb(receptor_source, receptor_pdb)convert_structure_to_pdb(best_pose_pdbqt, best_pose_pdb)# This ligand conversion removes hydrogens and writes CONECT records.convert_ligand_pose_to_ligplot_pdb(best_pose_pdbqt, best_pose_ligplot_pdb)# Keep a normal complex and a LigPlot+-ready complex.combine_protein_and_ligand_pdb(receptor_pdb, best_pose_ligplot_pdb, best_complex_pdb)shutil.copy2(best_complex_pdb, best_complex_ligplot_pdb)summary_json = work_dir / "summary.json"summary_payload = {11 unmodified lines"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_pose_ligplot_pdb": export_dir / "best_ligand_pose_ligplot_ready.pdb","best_complex_pdb": export_dir / "best_protein_ligand_complex.pdb","best_complex_ligplot_pdb": export_dir / "best_protein_ligand_complex_LigPlot_ready.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_pose_ligplot_pdb, out_map["best_pose_ligplot_pdb"])shutil.copy2(best_complex_pdb, out_map["best_complex_pdb"])shutil.copy2(best_complex_ligplot_pdb, out_map["best_complex_ligplot_pdb"])shutil.copy2(summary_json, out_map["summary_json"])zip_path = export_dir / "docking_results_bundle.zip"186 unmodified lines)with d2:with open(outputs["best_complex_ligplot_pdb"], "rb") as f:st.download_button("Download LigPlot+-ready best complex PDB",f.read(),file_name="best_protein_ligand_complex_LigPlot_ready.pdb",mime="chemical/x-pdb",)
qsar_core_streamlit.py+146-25