Commit 51308a45 by Gianluca LOMBARDI

Populate repository

parent 6a79e497
logs/
__pycache__/
\ No newline at end of file
# gemme-utils
## Overview
gemme-utils is a collection of utilities for handling and processing data related to [GEMME](http://www.lcqb.upmc.fr/GEMME) software and its updated version [ESCOTT](http://gitlab.lcqb.upmc.fr/tekpinar/PRESCOTT/). These utilities include scripts for preparing PDB files, running Docker containers, and plotting scores on protein structures using PyMOL.
## Requirements
- Python 3.7+
- BioPython (for PDB processing)
- Docker (for running GEMME/ESCOTT)
- Pandas (for processing prediction files)
- PyMOL (for plotting scores on protein structures)
## Installation
To install the required Python packages in a dedicated `conda` environment, run the following:
```bash
conda create -n gemme-env python=3.10
conda install biopython pandas
```
To execute the scripts from any directory, clone the repository and add it to `PATH`:
```bash
export PATH="/path/to/this/directory:$PATH"
```
### PyMOL
Official PyMOL software can be installed from [https://www.pymol.org/](https://www.pymol.org/) and it requires a valid license to be used. The provided bundles also include a version of Python.
An open-source version of PyMOL is available at [https://github.com/schrodinger/pymol-open-source](https://github.com/schrodinger/pymol-open-source).
### Docker
Docker can be installed through the Docker Desktop application from [https://www.docker.com/](https://www.docker.com/), and it is available for Linux, Windows and MacOS.
For some Linux distributions, it is also possible to install only Docker Engine, that allows to communicate with Docker server via command line interface (CLI). Download the appropriate version of Docker Engine from [https://docs.docker.com/engine/](https://docs.docker.com/engine/).
For Linux distributions, check out how to install Docker without root privileges at [https://docs.docker.com/engine/security/rootless/](https://docs.docker.com/engine/security/rootless/). On Windows and MacOS, instead, permissions can modified from Docker Desktop settings.
## Scripts
### prepare_alignment.py
Prepare a FASTA-like alignment for use with GEMME/ESCOTT by:
- Removing lowercase letters from sequences.
- Converting gap-like characters (`.`) into `-`.
- Removing positions containing gaps in the query sequence.
- Shortening headers to a maximum length of 50 characters.
The processed alignment is saved in the same directory as the input file.
The output file will have the same name of the input alignment file,
with `_processed.fasta` appended.
```bash
usage: prepare_alignment.py [-h] alignment_file
positional arguments:
alignment_file Path to the FASTA-like alignment file.
Example: python prepare_alignment.py test_data/trxf2.a3m
```
### prepare_pdb.py
Reformat a PDB file such that it can be used as input for ESCOTT, by removing all residues that are not part of the input sequence.
Requirements: BioPython
```bash
usage: prepare_pdb.py [-h] pdb_file alignment_file
positional arguments:
pdb_file Path to the input PDB file.
alignment_file Path to the alignment file in FASTA format,
with the query sequence as first entry.
Example: python prepare_pdb.py test_data/blat-af2 test_data/aliBLAT.fasta
```
### docker_run.py
Run GEMME or ESCOTT in a Docker container. It is possible to specify multiple input alignment files and select the number of parallel processes to use. For each alignment file, a separate Docker container will be created.
If the Docker image is not available locally, the script will try to pull it
from Docker Hub.
Requirements: `sudo`-less Docker installed and running
```bash
usage: docker_run.py [-h] [-n NUM_PROCESSES] software alignment_files [alignment_files ...] ...
positional arguments:
software Software to run, either GEMME or ESCOTT (case-insensitive).
alignment_files Paths to the alignment files in valid FASTA format.
additional_args Additional arguments to pass to the Docker container
in the form --key value or -k value.
options:
-n NUM_PROCESSES, --num_processes NUM_PROCESSES
Number of parallel processes to use. Default: 1.
Note: each process will run on a separate Docker
container, and will spawn additional threads during
the execution. To avoid overloading the system, it
is recommended to set the maximum value to the number
of available CPU cores / 8.
Example: python docker_run.py escott test_data/aliBLAT.fasta -n 1 \
--pdbfile test_data/blat-af2.fasta -m test_data/BLAT_ECOLX_Stiffler_2015_experimental.dat
```
### plot_on_structure.py
Plot GEMME/ESCOTT average per-position scores on the structure of the protein in a PyMOL session. The script will create a PyMOL session and it will color the structure
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
```bash
usage: plot_on_structure.py [-h] [--save] prediction_file pdb_file
positional arguments:
prediction_file Path to the prediction file.
pdb_file Path to the PDB file.
options:
-h, --help show this help message and exit
--save Save the colored structure as a PSE file.
Example: python plot_on_structure.py test_data/BLAT_normPred_evolCombi_test.txt test_data/blat-af2.pdb
```
## Contact Information
For any questions, issues, or contributions, please contact gianluca.lombardi@sorbonne-universite.fr
\ No newline at end of file
"""Runs GEMME or ESCOTT in a Docker container.
It is possible to specify multiple input alignment files and select
the number of parallel processes to use. For each alignment file, a
separate Docker container will be created.
If the Docker image is not available locally, the script will try to
pull it from Docker Hub.
Requirements:
- Docker software (installed and running)
"""
import argparse
import os
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Literal
Software = Literal["GEMME", "ESCOTT"]
_DOCKER_IMAGE = {
"GEMME": "elodielaine/gemme:gemme",
"ESCOTT": "tekpinar/prescott-docker:v1.6.0"
}
class DockerRunner:
"""Handles execution of GEMME or ESCOTT within a Docker container."""
def __init__(self, software: str, alignment_file: str, additional_args: str = ""):
self.software = software
self.docker_image = self._validate_software()
alignment_file = Path(alignment_file).absolute() # absolute path required for Docker
self.alignment_file = alignment_file.name
self.input_dir = alignment_file.parent
self.args = additional_args
self._check_docker_access()
self._inspect_docker_image()
print(
f"Running {self.software} with alignment file: {self.alignment_file} in input"
f" directory {self.input_dir}\n"
f"Additional arguments: {self.args if self.args != '' else None}"
)
def _validate_software(self) -> str:
"""Validates the software selection and returns the corresponding Docker image."""
if self.software not in _DOCKER_IMAGE:
raise ValueError("Invalid software. Must be either 'GEMME' or 'ESCOTT'.")
return _DOCKER_IMAGE[self.software]
def _check_docker_access(self) -> None:
"""Ensures that Docker is accessible."""
try:
subprocess.run(["docker", "info"], capture_output=True, check=True)
except subprocess.CalledProcessError as e:
raise RuntimeError(
"Docker is not accessible. Ensure it is installed and running."
) from e
def _inspect_docker_image(self) -> None:
"""Ensures the required Docker image is available locally, pulling it if necessary."""
try:
subprocess.run(
["docker", "inspect", self.docker_image],
capture_output=True,
check=True,
text=True,
)
print(f"Docker image {self.docker_image} is available locally.")
except subprocess.CalledProcessError as e:
error_message = e.stderr.strip()
if "No such object" in error_message:
print(
f"Image {self.docker_image} not found locally. Trying pulling from Docker"
" Hub..."
)
try:
subprocess.run(["docker", "pull", self.docker_image], check=True)
except subprocess.CalledProcessError as pull_error:
raise RuntimeError(
f"Error pulling Docker image: {pull_error.stderr}"
) from pull_error
else:
raise RuntimeError(f"Error checking Docker image: {error_message}") from e
def _build_docker_command(self) -> list[str]:
"""Constructs the Docker command to run the software."""
# Define the base command
mount_option = f"type=bind,source={self.input_dir},target=/project"
base_cmd = f"docker run -ti --rm --mount {mount_option} {self.docker_image} bash -c "
# Define the command inside the container
if self.software == "GEMME":
bash_cmd = (
f"python2.7 $GEMME_PATH/gemme.py {self.alignment_file} "
f"-f {self.alignment_file} -r input"
)
else:
bash_cmd = f"escott {self.alignment_file}"
# Add additional arguments
args = [arg.split("/")[-1] for arg in self.args.split()]
bash_cmd = " ".join([bash_cmd] + args).rstrip()
print(f"Docker command: {bash_cmd}")
return base_cmd + f"'cd /project && {bash_cmd}'"
def run(self) -> None:
"""Runs the software inside a Docker container."""
cmd = self._build_docker_command()
# Run Docker process, stream output and capture errors
with subprocess.Popen(
cmd, shell=True, stdout=sys.stdout, stderr=subprocess.PIPE, text=True
) as process:
try:
# Read and print stderr output
for line in process.stderr:
print(line.strip(), flush=True)
process.wait()
if process.returncode != 0:
raise RuntimeError(
f"Error running {self.software}. Exit code: {process.returncode}"
)
print(f"{self.software} ran successfully. Output files saved in {self.input_dir}")
except Exception as e:
process.terminate()
process.wait()
raise e
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"software",
type=str,
help="Software to run, either GEMME or ESCOTT (case-insensitive).",
)
parser.add_argument(
"alignment_files",
type=str,
nargs="+",
help="Paths to the alignment files in valid FASTA format.",
)
parser.add_argument(
"-n",
"--num_processes",
type=int,
default=1,
help="""Number of parallel processes to use. Default: 1.
Note: each process will run on a separate Docker
container, and will spawn additional threads during
the execution. To avoid overloading the system, it
is recommended to set the maximum value to the number
of available CPU cores / 8.
""",
)
parser.add_argument(
"additional_args",
nargs=argparse.REMAINDER,
help="""Additional arguments to pass to the Docker container
in the form --key value or -k value.
""",
)
args = parser.parse_args()
args.software = args.software.upper()
# get number of available CPU cores to limit the number of concurrent processes
num_cores = os.cpu_count()
args.num_processes = min(args.num_processes, num_cores // 8)
print(f"Number of available CPU cores: {num_cores}. Using {args.num_processes} processes.")
# convert additional arguments to a string
args.additional_args = " ".join(args.additional_args)
return args
def _run_docker(software: Software, alignment_file: str, additional_args: str) -> None:
"""Runs GEMME or ESCOTT in a Docker container"""
runner = DockerRunner(software, alignment_file, additional_args)
runner.run()
def run_docker(
software: Software, alignment_files: list[str], num_processes: int, additional_args: str
) -> None:
"""Runs GEMME or ESCOTT in a Docker container, passing the alignment file
and additional arguments as input.
Output files will be saved in the same directory as the alignment file.
For the list of available arguments, see the documentation of the respective
software.
The function does not allow to specify different arguments for each alignment file.
Args:
software: Software to run. Either "GEMME" or "ESCOTT".
alignment_files: Paths to the alignment files in valid FASTA format.
num_processes: Number of parallel processes to use.
**kwargs: Additional arguments to pass to the Docker container. All
additional input files should be in the same directory as the
alignment file.
Returns:
None
"""
if len(alignment_files) < num_processes:
raise ValueError(
"Number of processes must be less than or equal to the number of provided alignment"
" files."
)
def run_single_process(alignment_file: str) -> None:
_run_docker(software, alignment_file, additional_args)
if num_processes > 1:
with ThreadPoolExecutor(max_workers=num_processes) as executor:
executor.map(run_single_process, alignment_files)
else:
for alignment_file in alignment_files:
run_single_process(alignment_file)
if __name__ == "__main__":
args = _parse_args()
run_docker(**vars(args))
"""Plot GEMME/ESCOTT average per-position scores on the structure
of the protein in a PyMOL session.
Requirements:
- PyMOL software
- Pandas
The script will create a PyMOL session and it will color the structure
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.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("Pandas is required to run this script.")
import argparse
import subprocess
import time
from pathlib import Path
class PymolSession:
"""Manages a PyMOL subprocess session."""
def __init__(self):
cmd = ["pymol", "-p"] # GUI mode
self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, text=True)
time.sleep(2) # Wait for PyMOL to start
def __call__(self, command: str) -> None:
"""Sends a command to the PyMOL session."""
self.process.stdin.write(command + "\n")
self.process.stdin.flush()
def close(self) -> None:
"""Closes the PyMOL session safely."""
self.process.stdin.close()
self.process.wait()
self.process.terminate()
def _load_scores(prediction_file: str) -> pd.DataFrame:
"""Load the scores from the prediction file."""
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()
else:
raise ValueError("Invalid file format. Must be either CSV or TXT.")
scores.fillna(0, inplace=True) # set NaN values to 0
return scores
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)
# find minimum and maximum scores
min_score = scores.min()
max_score = scores.max()
if min_score >= 0 and max_score <= 1:
print("Scores are ranksorted. Higher scores identify more important positions.")
cmap = "blue_white_red"
else:
print("Scores are not ranksorted. Lower scores identify more important positions.")
cmap = "red_white_blue"
# Start PyMOL session
pms = PymolSession()
try:
pms(f"load {pdb_file}")
pms("show cartoon")
# 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'b={score}')"
)
time.sleep(2) # Wait for the scores to be set
pms(f"spectrum b, {cmap}, minimum={min_score}, maximum={max_score}")
# Add colorbar
pms(f"ramp_new colorbar, {mol}, [{min_score}, {max_score}], {cmap.split('_')}")
# Save the session if required
if save:
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
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("prediction_file", help="Path to the prediction file.")
parser.add_argument("pdb_file", help="Path to the PDB file.")
parser.add_argument(
"--save", action="store_true", help="Save the colored structure as a PSE file."
)
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()
"""Prepare alignment for GEMME/ESCOTT.
This script prepares a FASTA-like alignment for use with GEMME/ESCOTT by:
- Removing lowercase letters from sequences.
- Converting gap-like characters (`.`) into `-`.
- Removing positions containing gaps in the query sequence.
- Shortening headers to a maximum length of 50 characters.
The processed alignment is saved in the same directory as the input file.
The output file will have the same name of the input `alignment_file`,
with `_processed.fasta` appended.
"""
import argparse
import string
from pathlib import Path
class FastaDict:
"""A dictionary-like object for FASTA records and sequences."""
def __init__(self, records: list[str], sequences: list[str]):
self.records = records
self.sequences = sequences
@classmethod
def parse(cls, input_file: Path):
"""Parses a FASTA-like file into a structured dictionary.
- Removes lowercase letters from sequences.
- Converts gap-like characters (`.`) into `-`.
"""
records, sequences = [], []
translator = str.maketrans("", "", string.ascii_lowercase)
with open(input_file, "r") as f:
record, sequence = None, []
for line in map(str.strip, f):
if not line or line.startswith("#"): # Skip empty/comment lines
continue
if line.startswith(">"):
if record is not None:
records.append(record)
sequences.append("".join(sequence))
record, sequence = line.split()[0][1:], []
else:
sequence.append(line.translate(translator).replace(".", "-"))
if record is not None:
records.append(record)
sequences.append("".join(sequence))
return cls(records, sequences)
def write(self, output_file: Path):
"""Writes a FastaDict to a FASTA file."""
with open(output_file, "w") as f:
for record, sequence in zip(self.records, self.sequences):
f.write(f">{record}\n{sequence}\n")
def _shorten_headers(fasta: FastaDict, max_length: int = 50) -> FastaDict:
"""Shortens FASTA headers to a maximum length."""
return FastaDict(
records=[record[:max_length] for record in fasta.records],
sequences=fasta.sequences,
)
def _remove_query_gaps(alignment: FastaDict) -> FastaDict:
"""Removes positions containing gaps in the query sequence."""
query_sequence = alignment.sequences[0]
gap_indices = {i for i, c in enumerate(query_sequence) if c == "-"}
new_sequences = [
"".join(c for i, c in enumerate(seq) if i not in gap_indices)
for seq in alignment.sequences
]
return FastaDict(alignment.records, new_sequences)
def prepare_alignment(alignment_file: Path) -> None:
"""Converts a FASTA-like alignment into FASTA format for GEMME/ESCOTT:
- Removes lowercase letters from sequences.
- Converts gap-like characters (`.`) into `-`.
- Removes positions containing gaps in the query sequence.
- Shortens headers to a maximum length of 50 characters.
The processed alignment is saved in the same directory as the input file.
The output file will have the same name of the input `alignment_file`,
with `_processed.fasta` appended.
Args:
alignment_file: Path to the FASTA-like alignment file.
Returns:
None
"""
alignment_file = Path(alignment_file)
alignment = FastaDict.parse(alignment_file)
# Ensure all sequences are of equal length
seq_length = len(alignment.sequences[0])
if any(len(seq) != seq_length for seq in alignment.sequences):
raise ValueError("Sequences in the provided alignment have different lengths.")
alignment = _remove_query_gaps(alignment)
alignment = _shorten_headers(alignment)
output_file = alignment_file.with_name(f"{alignment_file.stem}_processed.fasta")
alignment.write(output_file)
print(f"Alignment saved to {output_file}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("alignment_file", help="Path to the FASTA-like alignment file.")
args = parser.parse_args()
prepare_alignment(args.alignment_file)
"""Reformat PDB file such that it can be used as input for ESCOTT,
by removing all residues that are not part of the input sequence.
Requirements:
- BioPython
"""
try:
from Bio import PDB
except ImportError:
raise ImportError("BioPython is required to run this script.")
import argparse
from pathlib import Path
class ResidueSelect(PDB.Select):
"""Selects residues based on their ids."""
def __init__(self, residue_numbers: list[int]):
self.residue_numbers = residue_numbers
def accept_residue(self, residue) -> bool:
return residue.id[1] in self.residue_numbers
def _extract_query(file_path: str) -> str:
"""Extract lines between the first and second lines starting with '>'.
Args:
file_path (str): Path to the input file.
Returns:
list[str]: Lines between the first and second lines starting with '>'.
"""
lines_between = []
with open(file_path, "r") as file:
header = False
for line in file:
if line.startswith(">"):
if header:
break
header = True
elif header:
lines_between.append(line.strip())
return "".join(lines_between)
def prepare_pdb(pdb_file: str, alignment_file: str) -> None:
"""Extracts sequence from PDB file and save a new PDB file with only
the residues of the input sequence.
Args:
pdb_file (str): Path to the input PDB file.
alignment_file (str): Path to the alignment file in FASTA format,
with the query sequence as first entry.
Returns:
None
"""
# Get query sequence from the alignment file
sequence = _extract_query(alignment_file)
# Load the PDB file
pdb_file = Path(pdb_file)
parser = PDB.PDBParser(QUIET=True)
structure = parser.get_structure("structure", pdb_file)
# Extract the sequence from the PDB file
ppb = PDB.PPBuilder()
for model in structure:
for chain in model:
chain_sequence = "".join([str(pp.get_sequence()) for pp in ppb.build_peptides(chain)])
if sequence in chain_sequence:
residue_numbers = [
residue.id[1] for residue in chain if sequence in chain_sequence
]
break
io = PDB.PDBIO()
io.set_structure(structure)
output_pdb_file = pdb_file.with_name(f"{pdb_file.stem}_processed.pdb").as_posix()
io.save(output_pdb_file, ResidueSelect(residue_numbers))
print(f"Processed PDB file saved to {output_pdb_file}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("pdb_file", help="Path to the input PDB file.")
parser.add_argument(
"alignment_file",
help="""Path to the alignment file in FASTA format,
with the query sequence as first entry.
""",
)
args = parser.parse_args()
prepare_pdb(args.pdb_file, args.alignment_file)
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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