Commit 1658e3e3 by Gianluca LOMBARDI

Fix error in PDB indexing in plot_on_structure, update requirements

parent 70e3b18d
......@@ -157,7 +157,7 @@ based on the average per-position scores from the prediction file.
Red color indicates positions more sensible to mutations, while blue
indicates less sensible positions.
Requirements: PyMOL software, Pandas
Requirements: PyMOL software, Pandas, BioPython
```bash
usage: plot_on_structure.py [-h] [--save] prediction_file pdb_file
......
......@@ -4,6 +4,7 @@ of the protein in a PyMOL session.
Requirements:
- PyMOL software
- Pandas
- BioPython
The script will create a PyMOL session and it will color the structure
based on the average per-position scores from the prediction file.
......@@ -13,8 +14,9 @@ indicates less sensible positions.
try:
import pandas as pd
from Bio.PDB import PDBParser
except ImportError:
raise ImportError("Pandas is required to run this script.")
raise ImportError("Pandas and BioPython are required to run this script.")
import argparse
import subprocess
......@@ -47,7 +49,7 @@ def _load_scores(prediction_file: str) -> pd.DataFrame:
if prediction_file.endswith(".csv"):
scores = pd.read_csv(prediction_file, index_col=0)
elif prediction_file.endswith(".txt"):
scores = pd.read_csv(prediction_file, sep=r'\s+', index_col=0).transpose()
scores = pd.read_csv(prediction_file, sep=r"\s+", index_col=0).transpose()
else:
raise ValueError("Invalid file format. Must be either CSV or TXT.")
......@@ -55,21 +57,30 @@ def _load_scores(prediction_file: str) -> pd.DataFrame:
return scores
def plot_on_structure(
prediction_file: str, pdb_file: str, save: bool = False
) -> None:
def _extract_pdb_ids(pdb_file: str) -> list[int]:
"""Extract the residue IDs from the PDB file."""
parser = PDBParser(QUIET=True)
structure = parser.get_structure("structure", pdb_file)
residues = structure.get_residues()
return [residue.id[1] for residue in residues]
def plot_on_structure(prediction_file: str, pdb_file: str, save: bool = False) -> None:
"""Plot the average per-position scores on the structure of the protein."""
pdb_file = Path(pdb_file)
mol = pdb_file.stem
# Load scores and compute average per-position
scores = _load_scores(prediction_file)
scores = scores.mean(axis=1)
print(scores.shape)
scores = scores.mean(axis=1).tolist()
# Extract residue IDs from the PDB file
residue_ids = _extract_pdb_ids(pdb_file)
# find minimum and maximum scores
min_score = scores.min()
max_score = scores.max()
min_score = min(scores)
max_score = max(scores)
if min_score >= 0 and max_score <= 1:
print("Scores are ranksorted. Higher scores identify more important positions.")
cmap = "blue_white_red"
......@@ -87,7 +98,7 @@ def plot_on_structure(
# Set scoes as B-factors and color by spectrum
pms(f"alter {mol}, b=10")
pms(
f"for res_id, score in enumerate({list(scores)}): cmd.alter(f'resi {{res_id + 1}}',"
f"for res_id, score in zip({residue_ids}, {scores}): cmd.alter(f'resi {{res_id}}',"
" f'b={score}')"
)
time.sleep(2) # Wait for the scores to be set
......@@ -101,12 +112,18 @@ def plot_on_structure(
pms(f"save {mol}_colored.pse")
pms.process.wait()
print(f"Colored structure saved as {mol}_colored.pse")
return pms
except Exception as e:
pms.close()
raise e
try:
print("PyMOL session is running. Press Ctrl+C to close.")
pms.process.wait() # Keep PyMOL open
except KeyboardInterrupt:
print("Closing PyMOL session.")
pms.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
......@@ -119,11 +136,4 @@ if __name__ == "__main__":
)
args = parser.parse_args()
pms = plot_on_structure(args.prediction_file, args.pdb_file, args.save)
try:
print("PyMOL session is running. Press Ctrl+C to close.")
pms.process.wait() # Keep PyMOL open
except KeyboardInterrupt:
print("Closing PyMOL session.")
pms.close()
plot_on_structure(args.prediction_file, args.pdb_file, args.save)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment