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. ...@@ -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 Red color indicates positions more sensible to mutations, while blue
indicates less sensible positions. indicates less sensible positions.
Requirements: PyMOL software, Pandas Requirements: PyMOL software, Pandas, BioPython
```bash ```bash
usage: plot_on_structure.py [-h] [--save] prediction_file pdb_file usage: plot_on_structure.py [-h] [--save] prediction_file pdb_file
......
...@@ -4,17 +4,19 @@ of the protein in a PyMOL session. ...@@ -4,17 +4,19 @@ of the protein in a PyMOL session.
Requirements: Requirements:
- PyMOL software - PyMOL software
- Pandas - Pandas
- BioPython
The script will create a PyMOL session and it will color the structure The script will create a PyMOL session and it will color the structure
based on the average per-position scores from the prediction file. based on the average per-position scores from the prediction file.
Red color indicates positions more sensible to mutations, while blue Red color indicates positions more sensible to mutations, while blue
indicates less sensible positions. indicates less sensible positions.
""" """
try: try:
import pandas as pd import pandas as pd
from Bio.PDB import PDBParser
except ImportError: 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 argparse
import subprocess import subprocess
...@@ -44,10 +46,10 @@ class PymolSession: ...@@ -44,10 +46,10 @@ class PymolSession:
def _load_scores(prediction_file: str) -> pd.DataFrame: def _load_scores(prediction_file: str) -> pd.DataFrame:
"""Load the scores from the prediction file.""" """Load the scores from the prediction file."""
if prediction_file.endswith(".csv"): if prediction_file.endswith(".csv"):
scores = pd.read_csv(prediction_file, index_col=0) scores = pd.read_csv(prediction_file, index_col=0)
elif prediction_file.endswith(".txt"): 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: else:
raise ValueError("Invalid file format. Must be either CSV or TXT.") raise ValueError("Invalid file format. Must be either CSV or TXT.")
...@@ -55,28 +57,37 @@ def _load_scores(prediction_file: str) -> pd.DataFrame: ...@@ -55,28 +57,37 @@ def _load_scores(prediction_file: str) -> pd.DataFrame:
return scores return scores
def plot_on_structure( def _extract_pdb_ids(pdb_file: str) -> list[int]:
prediction_file: str, pdb_file: str, save: bool = False """Extract the residue IDs from the PDB file."""
) -> None: 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.""" """Plot the average per-position scores on the structure of the protein."""
pdb_file = Path(pdb_file) pdb_file = Path(pdb_file)
mol = pdb_file.stem mol = pdb_file.stem
# Load scores and compute average per-position # Load scores and compute average per-position
scores = _load_scores(prediction_file) scores = _load_scores(prediction_file)
scores = scores.mean(axis=1) scores = scores.mean(axis=1).tolist()
print(scores.shape)
# Extract residue IDs from the PDB file
residue_ids = _extract_pdb_ids(pdb_file)
# find minimum and maximum scores # find minimum and maximum scores
min_score = scores.min() min_score = min(scores)
max_score = scores.max() max_score = max(scores)
if min_score >= 0 and max_score <= 1: if min_score >= 0 and max_score <= 1:
print("Scores are ranksorted. Higher scores identify more important positions.") print("Scores are ranksorted. Higher scores identify more important positions.")
cmap = "blue_white_red" cmap = "blue_white_red"
else: else:
print("Scores are not ranksorted. Lower scores identify more important positions.") print("Scores are not ranksorted. Lower scores identify more important positions.")
cmap = "red_white_blue" cmap = "red_white_blue"
# Start PyMOL session # Start PyMOL session
pms = PymolSession() pms = PymolSession()
...@@ -87,25 +98,31 @@ def plot_on_structure( ...@@ -87,25 +98,31 @@ def plot_on_structure(
# Set scoes as B-factors and color by spectrum # Set scoes as B-factors and color by spectrum
pms(f"alter {mol}, b=10") pms(f"alter {mol}, b=10")
pms( 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}')" " f'b={score}')"
) )
time.sleep(2) # Wait for the scores to be set time.sleep(2) # Wait for the scores to be set
pms(f"spectrum b, {cmap}, minimum={min_score}, maximum={max_score}") pms(f"spectrum b, {cmap}, minimum={min_score}, maximum={max_score}")
# Add colorbar # Add colorbar
pms(f"ramp_new colorbar, {mol}, [{min_score}, {max_score}], {cmap.split('_')}") pms(f"ramp_new colorbar, {mol}, [{min_score}, {max_score}], {cmap.split('_')}")
# Save the session if required # Save the session if required
if save: if save:
pms(f"save {mol}_colored.pse") pms(f"save {mol}_colored.pse")
pms.process.wait() pms.process.wait()
print(f"Colored structure saved as {mol}_colored.pse") print(f"Colored structure saved as {mol}_colored.pse")
return pms
except Exception as e: except Exception as e:
pms.close() pms.close()
raise e 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__": if __name__ == "__main__":
...@@ -119,11 +136,4 @@ if __name__ == "__main__": ...@@ -119,11 +136,4 @@ if __name__ == "__main__":
) )
args = parser.parse_args() args = parser.parse_args()
pms = plot_on_structure(args.prediction_file, args.pdb_file, args.save) 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()
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