gapms 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of gapms might be problematic. Click here for more details.
- gapms-0.1.0/LICENSE +21 -0
- gapms-0.1.0/PKG-INFO +86 -0
- gapms-0.1.0/README.md +74 -0
- gapms-0.1.0/gapms/__init__.py +0 -0
- gapms-0.1.0/gapms/extract.py +132 -0
- gapms-0.1.0/gapms/filter.py +129 -0
- gapms-0.1.0/gapms/gtf_utils.py +18 -0
- gapms-0.1.0/gapms/main.py +91 -0
- gapms-0.1.0/gapms/mapping_utils.py +17 -0
- gapms-0.1.0/gapms/model_utils.py +157 -0
- gapms-0.1.0/gapms/peptide_utils.py +55 -0
- gapms-0.1.0/gapms/plotting.py +195 -0
- gapms-0.1.0/gapms/tools.py +56 -0
- gapms-0.1.0/gapms/translate.py +110 -0
- gapms-0.1.0/gapms.egg-info/PKG-INFO +86 -0
- gapms-0.1.0/gapms.egg-info/SOURCES.txt +20 -0
- gapms-0.1.0/gapms.egg-info/dependency_links.txt +1 -0
- gapms-0.1.0/gapms.egg-info/requires.txt +4 -0
- gapms-0.1.0/gapms.egg-info/top_level.txt +1 -0
- gapms-0.1.0/pyproject.toml +15 -0
- gapms-0.1.0/setup.cfg +4 -0
- gapms-0.1.0/setup.py +24 -0
gapms-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Qussai Abbas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
gapms-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gapms
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: GAP-MS is a pipeline designed to evaluate and refine predicted gene models by integrating proteogenomic evidence from mass spectrometry with in-silico gene predictions.
|
|
5
|
+
Author-email: Qussai Abbas <qussai.abbas@tum.de>
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: perl-xml-parser; platform_system == "Linux"
|
|
10
|
+
Requires-Dist: perl-xml-twig; platform_system == "Linux"
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# GAP-MS: **Gene Model Assessment using Peptides from Mass Spectrometry**
|
|
14
|
+
|
|
15
|
+
**GAP-MS** is a pipeline designed to evaluate and refine predicted gene models by integrating proteogenomic evidence from mass spectrometry with in-silico gene predictions. This approach leverages an iterative machine learning framework to classify predicted proteins as *supported* or *unsupported*, improving both specificity and overall accuracy of gene models.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## ๐ฆ Installation
|
|
20
|
+
|
|
21
|
+
We recommend setting up a dedicated Conda environment to manage dependencies:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
conda create -n gapms_env python=3.10 perl-xml-parser perl-xml-twig -c conda-forge
|
|
25
|
+
conda activate gapms_env
|
|
26
|
+
git clone https://github.com/qussai96/GAP-MS.git
|
|
27
|
+
cd GAP-MS
|
|
28
|
+
pip install -e .
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## ๐ Required Inputs
|
|
34
|
+
|
|
35
|
+
To run GAP-MS, you need the following input files:
|
|
36
|
+
|
|
37
|
+
1. **Gene models** in GTF or GFF format
|
|
38
|
+
2. **Translated protein sequences** (FASTA format) of the gene models
|
|
39
|
+
3. **Peptide list** plain text (.txt) file containing peptides identified from a mass spectrometry experiment [Each peptide should be on a separate line]
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## ๐งช Running the Pipeline
|
|
43
|
+
|
|
44
|
+
### Option 1: With translated protein FASTA file
|
|
45
|
+
|
|
46
|
+
If you already have the translated gene models in FASTA format:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
gapms -g annotations.gtf -a proteins.fasta -p peptides.txt [-o /path/to/output_directory]
|
|
50
|
+
```
|
|
51
|
+
> โน๏ธ **Note**: If the `-o` output directory is not specified, the results will be written to a folder named `GAPMS_Output` in the same directory as the GTF file.
|
|
52
|
+
|
|
53
|
+
### Option 2: With genome assembly file
|
|
54
|
+
|
|
55
|
+
If you only have the genome assembly (FASTA) and not the translated proteins, gapms will get the translated proteins from the assembly by running:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
gapms -g annotations.gtf -a assembly.fasta -p peptides.txt [-o /path/to/output_directory]
|
|
59
|
+
```
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## ๐ Optional: Use Custom Mapping File
|
|
63
|
+
|
|
64
|
+
If you prefer to use a custom peptide-to-protein mapping (instead of running `proteomapper`), use the `-m` option:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
gapms -g annotations.gtf -a assembly.fasta -m /path/to/mapping_file.tsv [-o /path/to/output_directory]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- The mapping file **must** include at least:
|
|
71
|
+
- `peptide`
|
|
72
|
+
- `protein` columns
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## ๐ Example Data
|
|
77
|
+
|
|
78
|
+
You can find examples of input files in the `tutorials/` directory to help you get started.
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## ๐ฌ Feedback & Issues
|
|
83
|
+
|
|
84
|
+
If you encounter bugs or have suggestions, please open an issue on the [GitHub repository](https://github.com/qussai96/GAP-MS/issues).
|
|
85
|
+
|
|
86
|
+
---
|
gapms-0.1.0/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# GAP-MS: **Gene Model Assessment using Peptides from Mass Spectrometry**
|
|
2
|
+
|
|
3
|
+
**GAP-MS** is a pipeline designed to evaluate and refine predicted gene models by integrating proteogenomic evidence from mass spectrometry with in-silico gene predictions. This approach leverages an iterative machine learning framework to classify predicted proteins as *supported* or *unsupported*, improving both specificity and overall accuracy of gene models.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## ๐ฆ Installation
|
|
8
|
+
|
|
9
|
+
We recommend setting up a dedicated Conda environment to manage dependencies:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
conda create -n gapms_env python=3.10 perl-xml-parser perl-xml-twig -c conda-forge
|
|
13
|
+
conda activate gapms_env
|
|
14
|
+
git clone https://github.com/qussai96/GAP-MS.git
|
|
15
|
+
cd GAP-MS
|
|
16
|
+
pip install -e .
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## ๐ Required Inputs
|
|
22
|
+
|
|
23
|
+
To run GAP-MS, you need the following input files:
|
|
24
|
+
|
|
25
|
+
1. **Gene models** in GTF or GFF format
|
|
26
|
+
2. **Translated protein sequences** (FASTA format) of the gene models
|
|
27
|
+
3. **Peptide list** plain text (.txt) file containing peptides identified from a mass spectrometry experiment [Each peptide should be on a separate line]
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## ๐งช Running the Pipeline
|
|
31
|
+
|
|
32
|
+
### Option 1: With translated protein FASTA file
|
|
33
|
+
|
|
34
|
+
If you already have the translated gene models in FASTA format:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
gapms -g annotations.gtf -a proteins.fasta -p peptides.txt [-o /path/to/output_directory]
|
|
38
|
+
```
|
|
39
|
+
> โน๏ธ **Note**: If the `-o` output directory is not specified, the results will be written to a folder named `GAPMS_Output` in the same directory as the GTF file.
|
|
40
|
+
|
|
41
|
+
### Option 2: With genome assembly file
|
|
42
|
+
|
|
43
|
+
If you only have the genome assembly (FASTA) and not the translated proteins, gapms will get the translated proteins from the assembly by running:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
gapms -g annotations.gtf -a assembly.fasta -p peptides.txt [-o /path/to/output_directory]
|
|
47
|
+
```
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## ๐ Optional: Use Custom Mapping File
|
|
51
|
+
|
|
52
|
+
If you prefer to use a custom peptide-to-protein mapping (instead of running `proteomapper`), use the `-m` option:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
gapms -g annotations.gtf -a assembly.fasta -m /path/to/mapping_file.tsv [-o /path/to/output_directory]
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- The mapping file **must** include at least:
|
|
59
|
+
- `peptide`
|
|
60
|
+
- `protein` columns
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## ๐ Example Data
|
|
65
|
+
|
|
66
|
+
You can find examples of input files in the `tutorials/` directory to help you get started.
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## ๐ฌ Feedback & Issues
|
|
71
|
+
|
|
72
|
+
If you encounter bugs or have suggestions, please open an issue on the [GitHub repository](https://github.com/qussai96/GAP-MS/issues).
|
|
73
|
+
|
|
74
|
+
---
|
|
File without changes
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
from Bio import SeqIO
|
|
5
|
+
|
|
6
|
+
from .gtf_utils import gtf_to_df_with_genes
|
|
7
|
+
from .mapping_utils import mapping_file_to_df
|
|
8
|
+
from .peptide_utils import (
|
|
9
|
+
get_gene_protein_specific_peps,
|
|
10
|
+
check_peptide_loc,
|
|
11
|
+
count_expected_peptides_with_missed_cleavages,
|
|
12
|
+
calculate_protein_coverage
|
|
13
|
+
)
|
|
14
|
+
from .plotting import (
|
|
15
|
+
plot_protein_coverage_hist,
|
|
16
|
+
plot_prediction_scores,
|
|
17
|
+
plot_psauron_scores,
|
|
18
|
+
plot_protein_metrics
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def extract_features(gtf_file, prediction_fasta, mapping_file, psauron_csv, output_dir):
|
|
22
|
+
gtf_df = gtf_to_df_with_genes(gtf_file)
|
|
23
|
+
transcripts_df = gtf_df[gtf_df['Type'].isin(['transcript', 'mRNA'])][['Suppl', 'Score']].rename(columns={'Suppl': 'Protein'})
|
|
24
|
+
transcripts_df['Prediction_score'] = pd.to_numeric(transcripts_df['Score'], errors='coerce').fillna(0)
|
|
25
|
+
transcripts_df = transcripts_df[['Protein', 'Prediction_score']]
|
|
26
|
+
|
|
27
|
+
gtf_df = gtf_df[gtf_df['Type'] == 'CDS']
|
|
28
|
+
gtf_df = gtf_df[gtf_df['Source'].isin(['AUGUSTUS', 'Helixer'])]
|
|
29
|
+
gtf_df['Isoforms'] = gtf_df.groupby('Gene')['Protein'].transform(lambda x: x.nunique())
|
|
30
|
+
gtf_df['Score'] = pd.to_numeric(gtf_df['Score'], errors='coerce')
|
|
31
|
+
gtf_df['Protein_Start'] = gtf_df.groupby('Protein')['Start'].transform('min')
|
|
32
|
+
gtf_df['Protein_End'] = gtf_df.groupby('Protein')['End'].transform('max')
|
|
33
|
+
gtf_df = gtf_df.merge(transcripts_df, on='Protein', how='left')
|
|
34
|
+
|
|
35
|
+
df_CDSs = gtf_df.copy().sort_values(by=['Protein', 'Start']).drop_duplicates(subset=['Seqid', 'Start', 'End', 'Protein'])
|
|
36
|
+
df_CDSs['cds_start'] = 0
|
|
37
|
+
df_CDSs['cds_end'] = 0
|
|
38
|
+
|
|
39
|
+
splice_sites_dict = {}
|
|
40
|
+
cds_start_map = {}
|
|
41
|
+
cds_end_map = {}
|
|
42
|
+
|
|
43
|
+
for protein, sub_df in df_CDSs.groupby('Protein'):
|
|
44
|
+
protein_cds_start = 0
|
|
45
|
+
total_protein_len = round((sub_df['End'] - sub_df['Start']).sum() / 3)
|
|
46
|
+
splice_sites_dict[protein] = len(sub_df) - 1
|
|
47
|
+
|
|
48
|
+
for idx, row in sub_df.iterrows():
|
|
49
|
+
cds_length = round((row['End'] - row['Start']) / 3)
|
|
50
|
+
if row['Strand'] == '+':
|
|
51
|
+
cds_start = protein_cds_start + 1
|
|
52
|
+
cds_end = protein_cds_start + cds_length
|
|
53
|
+
protein_cds_start = cds_end
|
|
54
|
+
else:
|
|
55
|
+
cds_end = total_protein_len
|
|
56
|
+
cds_start = total_protein_len - cds_length + 1
|
|
57
|
+
total_protein_len = cds_start - 1
|
|
58
|
+
|
|
59
|
+
cds_start_map[idx] = cds_start
|
|
60
|
+
cds_end_map[idx] = cds_end
|
|
61
|
+
|
|
62
|
+
df_CDSs.loc[cds_start_map.keys(), 'cds_start'] = list(cds_start_map.values())
|
|
63
|
+
df_CDSs.loc[cds_end_map.keys(), 'cds_end'] = list(cds_end_map.values())
|
|
64
|
+
|
|
65
|
+
gtf_df = gtf_df.merge(df_CDSs[['Protein', 'Start', 'cds_start', 'cds_end']], on=['Protein', 'Start'], how='left')
|
|
66
|
+
gtf_df['cds_start'] = gtf_df['cds_start'].astype('Int64')
|
|
67
|
+
gtf_df['cds_end'] = gtf_df['cds_end'].astype('Int64')
|
|
68
|
+
gtf_df['splice_sites'] = gtf_df['Protein'].map(splice_sites_dict)
|
|
69
|
+
|
|
70
|
+
mapping_df = mapping_file_to_df(mapping_file)
|
|
71
|
+
pep_df = get_gene_protein_specific_peps(gtf_df, mapping_df)
|
|
72
|
+
seq_dict = {record.id: str(record.seq).replace('I', 'L').replace('*', '') for record in SeqIO.parse(prediction_fasta, "fasta")}
|
|
73
|
+
pep_df['Prot_seq'] = pep_df['Protein'].map(seq_dict)
|
|
74
|
+
pep_df.dropna(subset=['Prot_seq'], inplace=True)
|
|
75
|
+
|
|
76
|
+
pep_df['pep_start'] = pep_df.apply(lambda row: row['Prot_seq'].find(row['Peptide']) + 1, axis=1)
|
|
77
|
+
pep_df['pep_end'] = pep_df.apply(lambda row: row['pep_start'] + len(row['Peptide']) - 1, axis=1)
|
|
78
|
+
pep_df['prot_len'] = pep_df['Prot_seq'].str.len()
|
|
79
|
+
pep_df['expected_peptides'] = pep_df['Prot_seq'].apply(count_expected_peptides_with_missed_cleavages)
|
|
80
|
+
pep_df.drop(columns='Prot_seq', inplace=True)
|
|
81
|
+
|
|
82
|
+
coverage_series = pep_df.groupby("Protein").apply(calculate_protein_coverage)
|
|
83
|
+
pep_df['protein_coverage'] = pep_df['Protein'].map(coverage_series)
|
|
84
|
+
|
|
85
|
+
peptide_features_df = pd.merge(gtf_df, pep_df, on=['Protein', 'Gene'])
|
|
86
|
+
peptide_features_df = peptide_features_df[[
|
|
87
|
+
'Peptide', 'Protein', 'Gene', 'Isoforms', 'splice_sites', 'Protein_specific',
|
|
88
|
+
'Gene_specific', 'cds_start', 'cds_end', 'pep_len',
|
|
89
|
+
'pep_start', 'pep_end', 'Prediction_score', 'prot_len', 'protein_coverage'
|
|
90
|
+
]]
|
|
91
|
+
|
|
92
|
+
cds_dict = peptide_features_df.groupby('Protein')[['cds_start', 'cds_end']].apply(lambda x: list(x.itertuples(index=False, name=None))).to_dict()
|
|
93
|
+
peptide_features_df['Splice_peptide'] = peptide_features_df.apply(lambda row: check_peptide_loc(row, cds_dict), axis=1)
|
|
94
|
+
|
|
95
|
+
peptide_features_df['Stop_peptide'] = np.where(peptide_features_df['pep_end'] == peptide_features_df['prot_len'], '+', '-')
|
|
96
|
+
peptide_features_df['Start_peptide'] = np.where(peptide_features_df['pep_start'] == 1, '+', '-')
|
|
97
|
+
|
|
98
|
+
proteins_scores_df = peptide_features_df.groupby("Protein").agg(
|
|
99
|
+
protein_length=("prot_len", "mean"),
|
|
100
|
+
protein_coverage=("protein_coverage", "mean"),
|
|
101
|
+
protein_isoforms=("Isoforms", "mean"),
|
|
102
|
+
splice_sites=("splice_sites", "mean"),
|
|
103
|
+
prediction_score=("Prediction_score", "mean"),
|
|
104
|
+
mapped_peptides=("Peptide", "count"),
|
|
105
|
+
start_peptides=("Start_peptide", lambda x: (x == "+").sum()),
|
|
106
|
+
stop_peptides=("Stop_peptide", lambda x: (x == "+").sum()),
|
|
107
|
+
protein_specific_peptides=("Protein_specific", lambda x: (x == "+").sum()),
|
|
108
|
+
gene_specific_peptides=("Gene_specific", lambda x: (x == "+").sum()),
|
|
109
|
+
splice_peptides=("Splice_peptide", lambda x: (x == "+").sum()),
|
|
110
|
+
internal_peptides=("Splice_peptide", lambda x: (x == "-").sum())
|
|
111
|
+
).reset_index()
|
|
112
|
+
|
|
113
|
+
proteins_scores_df['splice_sites'] = proteins_scores_df['Protein'].map(splice_sites_dict).fillna(0).astype(int)
|
|
114
|
+
# proteins_scores_df.to_csv(output_dir / 'protein_scores.tsv', sep='\t', index=False)
|
|
115
|
+
|
|
116
|
+
new_proteins = gtf_df[~gtf_df['Protein'].isin(proteins_scores_df['Protein'])]
|
|
117
|
+
new_entries = new_proteins[['Protein', 'Prediction_score']].drop_duplicates().copy()
|
|
118
|
+
new_entries['prediction_score'] = pd.to_numeric(new_entries['Prediction_score'], errors='coerce')
|
|
119
|
+
for col in proteins_scores_df.columns.difference(['Protein', 'prediction_score']):
|
|
120
|
+
new_entries[col] = 0
|
|
121
|
+
all_proteins_scores_df = pd.concat([proteins_scores_df, new_entries], ignore_index=True).drop(columns='Prediction_score')
|
|
122
|
+
|
|
123
|
+
psauron_df = pd.read_csv(psauron_csv, sep=',', names=['Protein', 'psauron_is_protein', 'psauron_score']).drop(columns='psauron_is_protein')
|
|
124
|
+
psauron_df['psauron_score'] = pd.to_numeric(psauron_df['psauron_score'], errors='coerce')
|
|
125
|
+
all_proteins_scores_df = pd.merge(all_proteins_scores_df, psauron_df, on='Protein', how='left')
|
|
126
|
+
all_proteins_scores_df['prediction_score'] = all_proteins_scores_df['prediction_score'].fillna(0)
|
|
127
|
+
all_proteins_scores_df.to_csv(output_dir / 'all_proteins_scores.tsv', sep='\t', index=False)
|
|
128
|
+
|
|
129
|
+
plot_protein_coverage_hist(all_proteins_scores_df, output_dir)
|
|
130
|
+
plot_prediction_scores(all_proteins_scores_df, output_dir)
|
|
131
|
+
plot_psauron_scores(all_proteins_scores_df, output_dir)
|
|
132
|
+
plot_protein_metrics(all_proteins_scores_df, output_dir)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from .extract import extract_features
|
|
6
|
+
from .gtf_utils import gtf_to_df_with_genes
|
|
7
|
+
from .model_utils import (
|
|
8
|
+
get_high_confident_proteins,
|
|
9
|
+
find_apply_score_filter,
|
|
10
|
+
train_iterative_model
|
|
11
|
+
)
|
|
12
|
+
from .plotting import (
|
|
13
|
+
plot_roc_curve,
|
|
14
|
+
plot_shap_summary,
|
|
15
|
+
plot_stacked_percentage_bar
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def filter_predictions(gtf_file, protein_fasta, mapping_file, psauron_csv, output_dir):
|
|
20
|
+
gtf_file = Path(gtf_file)
|
|
21
|
+
protein_fasta = Path(protein_fasta)
|
|
22
|
+
mapping_file = Path(mapping_file)
|
|
23
|
+
psauron_csv = Path(psauron_csv)
|
|
24
|
+
|
|
25
|
+
# Step 1: Extract features
|
|
26
|
+
extract_features(gtf_file, protein_fasta, mapping_file, psauron_csv, output_dir)
|
|
27
|
+
|
|
28
|
+
# Step 2: Load feature outputs
|
|
29
|
+
all_scores_path = output_dir / "all_proteins_scores.tsv"
|
|
30
|
+
all_proteins_df = pd.read_csv(all_scores_path, sep='\t')
|
|
31
|
+
|
|
32
|
+
# Step 3: Get GTF with Protein/Gene annotations
|
|
33
|
+
gtf_df = gtf_to_df_with_genes(gtf_file)
|
|
34
|
+
|
|
35
|
+
# Step 4: Find highly supported proteins
|
|
36
|
+
high_confident_df = get_high_confident_proteins(all_proteins_df)
|
|
37
|
+
high_confident_proteins = set(high_confident_df['Protein'].unique())
|
|
38
|
+
|
|
39
|
+
high_confident_proteins_gtf = gtf_df[gtf_df['Protein'].isin(high_confident_proteins)]
|
|
40
|
+
high_confident_proteins_gtf.drop(['Protein', 'Gene'], axis=1).to_csv(output_dir / "high_confident_proteins.gtf", sep="\t", index=False, header=False)
|
|
41
|
+
|
|
42
|
+
# Step 5: Apply ROC-based score filtering
|
|
43
|
+
all_proteins_df["Score"] = np.where(
|
|
44
|
+
all_proteins_df["psauron_score"] <= 0.1,
|
|
45
|
+
all_proteins_df["psauron_score"],
|
|
46
|
+
all_proteins_df["prediction_score"]
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
if gtf_df['Source'].iloc[0] == 'Helixer':
|
|
50
|
+
all_proteins_df["Score"] = all_proteins_df["psauron_score"]
|
|
51
|
+
prediction_supported = high_confident_proteins
|
|
52
|
+
else:
|
|
53
|
+
prediction_supported = find_apply_score_filter(
|
|
54
|
+
all_proteins_df, high_confident_proteins,
|
|
55
|
+
output_dir=output_dir,
|
|
56
|
+
plot_roc=plot_roc_curve
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# Save prediction-supported GTF
|
|
60
|
+
prediction_supported_gtf = gtf_df[gtf_df['Protein'].isin(prediction_supported)]
|
|
61
|
+
# prediction_supported_gtf.drop(['Protein', 'Gene'], axis=1).to_csv(output_dir / "prediction_supported_proteins.gtf", sep="\t", index=False, header=False)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
FEATURE_COLUMNS = [
|
|
65
|
+
"protein_coverage",
|
|
66
|
+
"protein_specific_peptides",
|
|
67
|
+
"gene_specific_peptides",
|
|
68
|
+
"splice_peptides",
|
|
69
|
+
"internal_peptides",
|
|
70
|
+
"start_peptides",
|
|
71
|
+
"stop_peptides",
|
|
72
|
+
"splice_sites",
|
|
73
|
+
"protein_isoforms"
|
|
74
|
+
]
|
|
75
|
+
# Step 6: Train iterative self-labeling model
|
|
76
|
+
labeled_df = train_iterative_model(
|
|
77
|
+
all_proteins_df,
|
|
78
|
+
feature_cols=FEATURE_COLUMNS,
|
|
79
|
+
pos_thr=0.90,
|
|
80
|
+
neg_thr=0.10,
|
|
81
|
+
n_iter=5,
|
|
82
|
+
shap_output_dir=output_dir,
|
|
83
|
+
plot_shap=plot_shap_summary
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# Save iterative results
|
|
87
|
+
iterative_proteins = set(labeled_df[labeled_df["final_label"] == 1]["Protein"])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
all_proteins = set(all_proteins_df["Protein"])
|
|
91
|
+
supported_proteins = prediction_supported | iterative_proteins
|
|
92
|
+
unsupported_proteins = all_proteins - supported_proteins
|
|
93
|
+
supported_proteins_gtf = gtf_df[gtf_df['Protein'].isin(supported_proteins)]
|
|
94
|
+
supported_proteins_gtf.drop(['Protein', 'Gene'], axis=1).to_csv(output_dir / "supported_proteins.gtf", sep="\t", index=False, header=False)
|
|
95
|
+
|
|
96
|
+
# Step 7: Save protein sets
|
|
97
|
+
def save_protein_list(protein_set, filename):
|
|
98
|
+
with open(output_dir / filename, "w") as f:
|
|
99
|
+
for p in sorted(protein_set):
|
|
100
|
+
f.write(f"{p}\n")
|
|
101
|
+
|
|
102
|
+
save_protein_list(all_proteins, "all_proteins.txt")
|
|
103
|
+
save_protein_list(high_confident_proteins, "high_confident_proteins.txt")
|
|
104
|
+
# save_protein_list(prediction_supported - high_confident_proteins, "prediction_only_proteins.txt")
|
|
105
|
+
# save_protein_list(iterative_proteins - prediction_supported, "iterative_only_proteins.txt")
|
|
106
|
+
save_protein_list(supported_proteins, "supported_proteins.txt")
|
|
107
|
+
save_protein_list(unsupported_proteins, "unsupported_proteins.txt")
|
|
108
|
+
|
|
109
|
+
# Step 8: Filter FASTA
|
|
110
|
+
output_fasta = output_dir / "supported_proteins.faa"
|
|
111
|
+
with open(protein_fasta) as fasta, open(output_fasta, "w") as out:
|
|
112
|
+
header, seq = "", ""
|
|
113
|
+
for line in fasta:
|
|
114
|
+
if line.startswith(">"):
|
|
115
|
+
if header and header[1:] in supported_proteins:
|
|
116
|
+
out.write(header + "\n" + seq + "\n")
|
|
117
|
+
header, seq = line.strip(), ""
|
|
118
|
+
else:
|
|
119
|
+
seq += line.strip()
|
|
120
|
+
if header and header[1:] in supported_proteins:
|
|
121
|
+
out.write(header + "\n" + seq + "\n")
|
|
122
|
+
|
|
123
|
+
plot_stacked_percentage_bar(len(supported_proteins), len(unsupported_proteins), output_dir)
|
|
124
|
+
print(f"\nPipeline completed\nOutputs written to: {output_dir}")
|
|
125
|
+
print(f"\nNumber of all proteins = {len(set(all_proteins_df['Protein']))}")
|
|
126
|
+
print(f"Number of high confident proteins = {len(high_confident_proteins)}")
|
|
127
|
+
# print(f"\n Number of low confident proteins = {len(low_confident_proteins)}")
|
|
128
|
+
print(f"Number of supported proteins = {len(supported_proteins)}")
|
|
129
|
+
print(f"Number of un-supported proteins = {len(unsupported_proteins)}")
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
def extract_id(suppl_value, pattern):
|
|
5
|
+
if isinstance(suppl_value, str):
|
|
6
|
+
match = re.search(pattern, suppl_value)
|
|
7
|
+
if match:
|
|
8
|
+
return match.group(1)
|
|
9
|
+
return None
|
|
10
|
+
|
|
11
|
+
def gtf_to_df_with_genes(gtf_file):
|
|
12
|
+
column_names = ['Seqid', 'Source', 'Type', 'Start', 'End', 'Score', 'Strand', 'Frame', 'Suppl']
|
|
13
|
+
df = pd.read_csv(gtf_file, sep='\t', index_col=False, names=column_names)
|
|
14
|
+
from .gtf_utils import extract_id
|
|
15
|
+
df['Gene'] = df.apply(lambda row: extract_id(row['Suppl'], r'Parent=([^;]+)') if row['Source'] in ['Helixer'] else extract_id(row['Suppl'], r'gene_id "([^"]+)"') , axis=1)
|
|
16
|
+
df['Protein'] = df.apply(lambda row: extract_id(row['Suppl'], r'Parent=([^;]+)') if row['Source'] in ['Helixer'] else extract_id(row['Suppl'], r'transcript_id "([^"]+)"'), axis=1)
|
|
17
|
+
df["Score"] = df["Score"].replace(".", 0).fillna(0)
|
|
18
|
+
return df
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
import warnings
|
|
3
|
+
import time
|
|
4
|
+
warnings.filterwarnings("ignore")
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
import argparse
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
|
|
11
|
+
from gapms.filter import filter_predictions
|
|
12
|
+
from gapms.tools import run_proteomapper, run_psauron
|
|
13
|
+
from gapms.translate import get_proteins_from_cds_gtf
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main():
|
|
17
|
+
start_time = time.time()
|
|
18
|
+
|
|
19
|
+
parser = argparse.ArgumentParser(
|
|
20
|
+
description="Filter GTF predictions using mass-spec data and mapping information."
|
|
21
|
+
)
|
|
22
|
+
parser.add_argument("-f", "--proteins", type=Path, help="Path to the protein FASTA file")
|
|
23
|
+
parser.add_argument("-g", "--gtf", type=Path, help="Path to the prediction GTF file (required if -f is not used)")
|
|
24
|
+
parser.add_argument("-a", "--assembly", type=Path, help="Path to the genome assembly file (required if -f is not used)")
|
|
25
|
+
parser.add_argument("-p", "--peptides", type=Path, help="Path to the peptides TXT file")
|
|
26
|
+
parser.add_argument("-m", "--mapping", type=Path, help="Optional precomputed peptide-to-protein mapping file")
|
|
27
|
+
parser.add_argument("-o", "--output", type=Path, help="Optional output directory")
|
|
28
|
+
|
|
29
|
+
args = parser.parse_args()
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
if args.output:
|
|
33
|
+
output_dir = args.output
|
|
34
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
35
|
+
else:
|
|
36
|
+
if args.gtf:
|
|
37
|
+
base_dir = args.gtf.parent.parent
|
|
38
|
+
output_dir = base_dir / "GAPMS_Output"
|
|
39
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
else:
|
|
41
|
+
parser.error("No GTF file was provided, you must specify --gtf.")
|
|
42
|
+
|
|
43
|
+
# Prepare logging
|
|
44
|
+
log_file_path = output_dir / "log.txt"
|
|
45
|
+
log_file = open(log_file_path, "w")
|
|
46
|
+
sys.stdout = log_file
|
|
47
|
+
sys.stderr = log_file
|
|
48
|
+
|
|
49
|
+
# Print to terminal
|
|
50
|
+
print(f"Starting GAP-MS. Check the log file in {log_file_path}", file=sys.__stdout__)
|
|
51
|
+
|
|
52
|
+
# Start the pipeline
|
|
53
|
+
if args.proteins:
|
|
54
|
+
protein_fasta = args.proteins
|
|
55
|
+
else:
|
|
56
|
+
if not (args.gtf and args.assembly):
|
|
57
|
+
raise ValueError("If --proteins is not provided, both --gtf and --assembly must be specified.")
|
|
58
|
+
print(f"{Path().cwd()} - Generating protein FASTA from GTF and genome assembly...")
|
|
59
|
+
protein_fasta = get_proteins_from_cds_gtf(args.assembly, args.gtf)
|
|
60
|
+
|
|
61
|
+
if args.mapping:
|
|
62
|
+
mapping = args.mapping
|
|
63
|
+
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Using provided mapping file: {mapping}")
|
|
64
|
+
else:
|
|
65
|
+
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Mapping peptides to proteins with Proteomapper....")
|
|
66
|
+
mapping = run_proteomapper(protein_fasta, args.peptides, output_dir)
|
|
67
|
+
|
|
68
|
+
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Running Psauron....")
|
|
69
|
+
psauron = run_psauron(protein_fasta, output_dir)
|
|
70
|
+
|
|
71
|
+
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Running gapms....")
|
|
72
|
+
filter_predictions(args.gtf, protein_fasta, mapping, psauron, output_dir)
|
|
73
|
+
|
|
74
|
+
# Final messages
|
|
75
|
+
total_time = (time.time() - start_time) / 60
|
|
76
|
+
print("\nโ
Pipeline completed", file=sys.__stdout__)
|
|
77
|
+
print(f"\nTotal time run: {total_time:.2f} minutes", file=sys.__stdout__)
|
|
78
|
+
|
|
79
|
+
except Exception as e:
|
|
80
|
+
print(f"\nโ An error occurred: {str(e)}", file=sys.__stdout__)
|
|
81
|
+
print(f"Please check the log file for more details: {log_file_path}", file=sys.__stdout__)
|
|
82
|
+
raise
|
|
83
|
+
|
|
84
|
+
finally:
|
|
85
|
+
try:
|
|
86
|
+
log_file.close()
|
|
87
|
+
except:
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
if __name__ == "__main__":
|
|
91
|
+
main()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
|
|
3
|
+
def mapping_file_to_df(mapping_file):
|
|
4
|
+
"""
|
|
5
|
+
Loads the peptide-to-protein mapping file and filters out unmapped entries.
|
|
6
|
+
|
|
7
|
+
Parameters:
|
|
8
|
+
- mapping_file (str or Path): Path to the mapping file with columns [Peptide, Protein, Location]
|
|
9
|
+
|
|
10
|
+
Returns:
|
|
11
|
+
- DataFrame with columns [Peptide, Protein, Location, pep_len]
|
|
12
|
+
"""
|
|
13
|
+
mapping_df = pd.read_csv(mapping_file, sep='\t', header=None, names=['Peptide', 'Protein', 'location'])
|
|
14
|
+
mapping_df = mapping_df[~mapping_df['Protein'].str.lower().eq('unmapped')]
|
|
15
|
+
mapping_df['pep_len'] = mapping_df['Peptide'].apply(len)
|
|
16
|
+
print(f'Total peptides loaded: {mapping_df["Peptide"].nunique()}')
|
|
17
|
+
return mapping_df
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from sklearn.model_selection import StratifiedKFold, RandomizedSearchCV
|
|
4
|
+
from xgboost import XGBClassifier
|
|
5
|
+
|
|
6
|
+
def calculate_sensitivity(scores, cutoff):
|
|
7
|
+
if not scores:
|
|
8
|
+
return 0.0
|
|
9
|
+
return sum(score >= cutoff for score in scores) / len(scores)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def calculate_specificity(all_scores, sp_scores, cutoff):
|
|
13
|
+
passed_all = [score for score in all_scores if score >= cutoff]
|
|
14
|
+
passed_sp = [score for score in sp_scores if score >= cutoff]
|
|
15
|
+
return len(passed_sp) / len(passed_all) if passed_all else 0.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def find_cutoff(proteins_scores_df, sp_proteins, output_dir=None, plot_roc=None):
|
|
19
|
+
scores = proteins_scores_df['Score'].tolist()
|
|
20
|
+
sp_scores = proteins_scores_df[proteins_scores_df['Protein'].isin(sp_proteins)]['Score'].tolist()
|
|
21
|
+
|
|
22
|
+
cutoffs = [x / 100 for x in range(100, -1, -1)]
|
|
23
|
+
tpr = [calculate_sensitivity(sp_scores, c) for c in cutoffs]
|
|
24
|
+
tnr = [calculate_specificity(scores, sp_scores, c) for c in cutoffs]
|
|
25
|
+
fpr = [1 - x for x in tnr]
|
|
26
|
+
|
|
27
|
+
for i in range(2, len(tpr)):
|
|
28
|
+
slope = (tpr[i] - tpr[i-1]) / (fpr[i] - fpr[i-1]) if (fpr[i] - fpr[i-1]) != 0 else float('inf')
|
|
29
|
+
if slope < 1:
|
|
30
|
+
cutoff = max(cutoffs[i], 0.69)
|
|
31
|
+
if plot_roc and output_dir:
|
|
32
|
+
plot_roc(fpr, tpr, cutoff, fpr[i], tpr[i], output_dir)
|
|
33
|
+
return cutoff
|
|
34
|
+
|
|
35
|
+
return 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def find_apply_score_filter(proteins_scores_df, sp_proteins, output_dir=None, plot_roc=None):
|
|
39
|
+
cutoff = find_cutoff(proteins_scores_df, sp_proteins, output_dir, plot_roc)
|
|
40
|
+
high_scoring = set(proteins_scores_df[proteins_scores_df['Score'] >= cutoff]['Protein'])
|
|
41
|
+
low_supported = set(proteins_scores_df[(proteins_scores_df['Score'] < cutoff) & proteins_scores_df['Protein'].isin(sp_proteins)]['Protein'])
|
|
42
|
+
return high_scoring | low_supported
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_high_confident_proteins(df):
|
|
46
|
+
high_confident = []
|
|
47
|
+
for _, group in df.groupby("Protein"):
|
|
48
|
+
for _, row in group.iterrows():
|
|
49
|
+
if row["protein_specific_peptides"] >= 2:
|
|
50
|
+
high_confident.append(row)
|
|
51
|
+
break
|
|
52
|
+
if row["gene_specific_peptides"] >= 2 and row["protein_specific_peptides"] >= 1:
|
|
53
|
+
high_confident.append(row)
|
|
54
|
+
break
|
|
55
|
+
if row["protein_coverage"] >= 0.5 and row["protein_specific_peptides"] >= 1:
|
|
56
|
+
high_confident.append(row)
|
|
57
|
+
break
|
|
58
|
+
if row["protein_coverage"] >= 0.7:
|
|
59
|
+
high_confident.append(row)
|
|
60
|
+
break
|
|
61
|
+
return pd.DataFrame(high_confident)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def train_iterative_model(df, feature_cols, pos_thr=0.90, neg_thr=0.10, n_iter=5, shap_output_dir=None, plot_shap=None):
|
|
65
|
+
df["label"] = np.nan
|
|
66
|
+
|
|
67
|
+
pos_mask = (
|
|
68
|
+
(df["protein_specific_peptides"] >= 2) |
|
|
69
|
+
(df["protein_coverage"] >= 0.7) |
|
|
70
|
+
((df["protein_specific_peptides"] >= 1) & (df["protein_coverage"] >= 0.5))
|
|
71
|
+
)
|
|
72
|
+
neg_mask = (
|
|
73
|
+
(df["mapped_peptides"] <= 1) &
|
|
74
|
+
(df["psauron_score"] < 0.5) &
|
|
75
|
+
(df["prediction_score"] < 0.5)
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
df.loc[pos_mask, "label"] = 1
|
|
79
|
+
df.loc[neg_mask, "label"] = 0
|
|
80
|
+
|
|
81
|
+
df_labeled = df.dropna(subset=["label"])
|
|
82
|
+
X_labeled = df_labeled[feature_cols]
|
|
83
|
+
y_labeled = df_labeled["label"]
|
|
84
|
+
|
|
85
|
+
# Check if there are any negative labels
|
|
86
|
+
if (y_labeled == 0).sum() == 0:
|
|
87
|
+
raise ValueError(
|
|
88
|
+
"No negative labels found in the labeled data.\n"
|
|
89
|
+
"Either the number of proteins in the fasta file is very low,\n"
|
|
90
|
+
"or all proteins are fully supported by peptides.\n"
|
|
91
|
+
"Stopping the pipeline."
|
|
92
|
+
)
|
|
93
|
+
else:
|
|
94
|
+
# Use StratifiedKFold to preserve class imbalance in each fold
|
|
95
|
+
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
|
|
96
|
+
|
|
97
|
+
# Initialize base model
|
|
98
|
+
base_model = XGBClassifier(eval_metric='logloss', random_state=42)
|
|
99
|
+
|
|
100
|
+
param_dist = {
|
|
101
|
+
'n_estimators': [100, 200],
|
|
102
|
+
'max_depth': [3, 5, 7],
|
|
103
|
+
'learning_rate': [0.01, 0.1],
|
|
104
|
+
'subsample': [0.8, 1.0],
|
|
105
|
+
'colsample_bytree': [0.8, 1.0],
|
|
106
|
+
'scale_pos_weight': [1, 2, 5]
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
# Set up RandomizedSearchCV
|
|
110
|
+
random_search = RandomizedSearchCV(
|
|
111
|
+
estimator=base_model,
|
|
112
|
+
param_distributions=param_dist,
|
|
113
|
+
n_iter=20, # Adjust this to explore more parameters if needed
|
|
114
|
+
scoring='roc_auc', # Use a scoring metric that handles imbalance well
|
|
115
|
+
cv=skf,
|
|
116
|
+
verbose=1,
|
|
117
|
+
random_state=42,
|
|
118
|
+
n_jobs=-1
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
# Fit RandomizedSearchCV on your labeled data
|
|
122
|
+
random_search.fit(X_labeled, y_labeled)
|
|
123
|
+
|
|
124
|
+
# Use the best estimator from the search
|
|
125
|
+
model = random_search.best_estimator_
|
|
126
|
+
|
|
127
|
+
if plot_shap and shap_output_dir:
|
|
128
|
+
plot_shap(model, X_labeled, shap_output_dir)
|
|
129
|
+
|
|
130
|
+
for _ in range(n_iter):
|
|
131
|
+
df_unlabeled = df[df["label"].isna()]
|
|
132
|
+
if df_unlabeled.empty:
|
|
133
|
+
break
|
|
134
|
+
|
|
135
|
+
X_unlabeled = df_unlabeled[feature_cols]
|
|
136
|
+
prob_pred = model.predict_proba(X_unlabeled)[:, 1]
|
|
137
|
+
|
|
138
|
+
new_pos = df_unlabeled.index[prob_pred >= pos_thr]
|
|
139
|
+
new_neg = df_unlabeled.index[prob_pred <= neg_thr]
|
|
140
|
+
|
|
141
|
+
df.loc[new_pos, "label"] = 1
|
|
142
|
+
df.loc[new_neg, "label"] = 0
|
|
143
|
+
|
|
144
|
+
df_labeled = df.dropna(subset=["label"])
|
|
145
|
+
y_labeled = df_labeled["label"]
|
|
146
|
+
X_labeled = df_labeled[feature_cols]
|
|
147
|
+
|
|
148
|
+
if y_labeled.nunique() == 2:
|
|
149
|
+
model = XGBClassifier(eval_metric='logloss', random_state=42)
|
|
150
|
+
model.fit(X_labeled, y_labeled)
|
|
151
|
+
|
|
152
|
+
if len(new_pos) == 0 and len(new_neg) == 0:
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
df["prob_pos"] = model.predict_proba(df[feature_cols])[:, 1]
|
|
156
|
+
df["final_label"] = (df["prob_pos"] >= 0.5).astype(int)
|
|
157
|
+
return df
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
def get_gene_protein_specific_peps(gtf_df, mapping_df):
|
|
5
|
+
pred_df = gtf_df[['Protein', 'Gene']]
|
|
6
|
+
pep_protein_gene_df = mapping_df.merge(pred_df, on='Protein', how='left').drop_duplicates().dropna()
|
|
7
|
+
peptide_protein_map = pep_protein_gene_df.groupby('Peptide')['Protein'].nunique()
|
|
8
|
+
|
|
9
|
+
peptide_gene_map = pep_protein_gene_df.groupby('Peptide')['Gene'].nunique()
|
|
10
|
+
|
|
11
|
+
pep_protein_gene_df['Protein_specific'] = pep_protein_gene_df['Peptide'].map(peptide_protein_map).eq(1).map({True: '+', False: '-'})
|
|
12
|
+
pep_protein_gene_df['Gene_specific'] = pep_protein_gene_df['Peptide'].map(peptide_gene_map).eq(1).map({True: '+', False: '-'})
|
|
13
|
+
|
|
14
|
+
return pep_protein_gene_df[['Peptide', 'Protein', 'Gene', 'pep_len', 'Protein_specific', 'Gene_specific']]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def check_peptide_loc(row, protein_cds_dict):
|
|
18
|
+
protein = row['Protein']
|
|
19
|
+
pep_start, pep_end = row['pep_start'], row['pep_end']
|
|
20
|
+
protein_cds = protein_cds_dict.get(protein, [])
|
|
21
|
+
|
|
22
|
+
for cds_start, cds_end in protein_cds:
|
|
23
|
+
if cds_start <= pep_start and cds_end >= pep_end:
|
|
24
|
+
return '-'
|
|
25
|
+
return '+'
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def count_expected_peptides_with_missed_cleavages(sequence, missed_cleavages=1):
|
|
29
|
+
cleavage_sites = [
|
|
30
|
+
i for i in range(len(sequence) - 1)
|
|
31
|
+
if sequence[i] in ['K', 'R'] and sequence[i + 1] != 'P'
|
|
32
|
+
]
|
|
33
|
+
num_cleavages = len(cleavage_sites)
|
|
34
|
+
total_peptides = sum((num_cleavages + missed) for missed in range(missed_cleavages + 1))
|
|
35
|
+
return total_peptides
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def calculate_protein_coverage(group):
|
|
39
|
+
prot_len = group["prot_len"].iloc[0]
|
|
40
|
+
intervals = group[["pep_start", "pep_end"]].to_numpy()
|
|
41
|
+
intervals = intervals[np.argsort(intervals[:, 0])]
|
|
42
|
+
|
|
43
|
+
merged_intervals = []
|
|
44
|
+
start, end = intervals[0]
|
|
45
|
+
|
|
46
|
+
for s, e in intervals[1:]:
|
|
47
|
+
if s <= end:
|
|
48
|
+
end = max(end, e)
|
|
49
|
+
else:
|
|
50
|
+
merged_intervals.append((start, end))
|
|
51
|
+
start, end = s, e
|
|
52
|
+
merged_intervals.append((start, end))
|
|
53
|
+
|
|
54
|
+
covered_length = sum(e - s + 1 for s, e in merged_intervals)
|
|
55
|
+
return round(covered_length / prot_len, 4)
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import matplotlib.pyplot as plt
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
def plot_protein_coverage_hist(df, output_dir):
|
|
6
|
+
plt.figure(figsize=(6, 4))
|
|
7
|
+
plt.hist(
|
|
8
|
+
df["protein_coverage"],
|
|
9
|
+
bins=20, density=True, color="navy", alpha=0.7, label="All proteins"
|
|
10
|
+
)
|
|
11
|
+
plt.hist(
|
|
12
|
+
df[df["protein_specific_peptides"] >= 2]["protein_coverage"],
|
|
13
|
+
bins=20, density=True, color="mediumseagreen", alpha=0.8, label="Supported proteins"
|
|
14
|
+
)
|
|
15
|
+
plt.yscale("log")
|
|
16
|
+
plt.xlabel("Protein coverage")
|
|
17
|
+
plt.ylabel("Density")
|
|
18
|
+
plt.title("Protein Coverage")
|
|
19
|
+
plt.legend()
|
|
20
|
+
plt.savefig(output_dir / 'Protein_coverage.png', dpi=300, bbox_inches='tight')
|
|
21
|
+
plt.close()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def plot_prediction_scores(df, output_dir):
|
|
25
|
+
plt.figure(figsize=(6, 4))
|
|
26
|
+
plt.hist(
|
|
27
|
+
df["prediction_score"],
|
|
28
|
+
bins=20, density=True, color="navy", alpha=0.7, label="All proteins"
|
|
29
|
+
)
|
|
30
|
+
plt.hist(
|
|
31
|
+
df[df["protein_specific_peptides"] >= 2]["prediction_score"],
|
|
32
|
+
bins=20, density=True, color="mediumseagreen", alpha=0.8, label="Supported proteins"
|
|
33
|
+
)
|
|
34
|
+
plt.yscale("log")
|
|
35
|
+
plt.xlabel("Prediction score")
|
|
36
|
+
plt.ylabel("Density")
|
|
37
|
+
plt.title("Prediction Scores")
|
|
38
|
+
plt.legend()
|
|
39
|
+
plt.savefig(output_dir / 'Prediction_scores.png', dpi=300, bbox_inches='tight')
|
|
40
|
+
plt.close()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def plot_psauron_scores(df, output_dir):
|
|
44
|
+
plt.figure(figsize=(6, 4))
|
|
45
|
+
plt.hist(
|
|
46
|
+
df["psauron_score"],
|
|
47
|
+
bins=20, density=True, color="navy", alpha=0.7, label="All proteins"
|
|
48
|
+
)
|
|
49
|
+
plt.hist(
|
|
50
|
+
df[df["protein_specific_peptides"] >= 2]["psauron_score"],
|
|
51
|
+
bins=20, density=True, color="mediumseagreen", alpha=0.8, label="Supported proteins"
|
|
52
|
+
)
|
|
53
|
+
plt.yscale("log")
|
|
54
|
+
plt.xlabel("Psauron score")
|
|
55
|
+
plt.ylabel("Density")
|
|
56
|
+
plt.title("Psauron Scores")
|
|
57
|
+
plt.legend()
|
|
58
|
+
plt.savefig(output_dir / 'Psauron_scores.png', dpi=300, bbox_inches='tight')
|
|
59
|
+
plt.close()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def plot_roc_curve(fpr, tpr, cutoff, fpr_cut, tpr_cut, output_dir):
|
|
63
|
+
plt.figure(figsize=(2, 3))
|
|
64
|
+
plt.plot(fpr, tpr, marker='o', linestyle='-', color='purple', alpha=0.9)
|
|
65
|
+
plt.axvline(x=fpr_cut, color='red', linestyle='-')
|
|
66
|
+
plt.text(fpr_cut + 0.02, tpr_cut, f"score = {cutoff}", fontsize=12, color="black")
|
|
67
|
+
plt.xlabel("False positive rate")
|
|
68
|
+
plt.ylabel("True positive rate")
|
|
69
|
+
plt.title("Score Cutoff")
|
|
70
|
+
plt.savefig(output_dir/ 'ROC_curve.png', dpi=300, bbox_inches='tight')
|
|
71
|
+
plt.close()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def plot_shap_summary(model, X_labeled, output_dir):
|
|
75
|
+
import shap
|
|
76
|
+
explainer = shap.Explainer(model)
|
|
77
|
+
shap_values = explainer(X_labeled)
|
|
78
|
+
shap.summary_plot(shap_values, X_labeled, show=False)
|
|
79
|
+
plt.savefig(output_dir/ 'Shap_summary_plot.png', bbox_inches='tight')
|
|
80
|
+
plt.close()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def plot_stacked_percentage_bar(value1, value2, output_dir):
|
|
84
|
+
# Compute total and percentages
|
|
85
|
+
total = value1 + value2
|
|
86
|
+
percent1 = value1 / total * 100
|
|
87
|
+
percent2 = value2 / total * 100
|
|
88
|
+
|
|
89
|
+
# Plot
|
|
90
|
+
fig, ax = plt.subplots(figsize=(2.5, 6)) # Tall format
|
|
91
|
+
bars1 = ax.bar(0, percent1, color='green', edgecolor='black')
|
|
92
|
+
bars2 = ax.bar(0, percent2, bottom=percent1, color='red', edgecolor='black')
|
|
93
|
+
|
|
94
|
+
# Add text inside bars
|
|
95
|
+
ax.text(0, percent1 / 2, f'{value1}', ha='center', va='center', fontsize=12, color='white')
|
|
96
|
+
ax.text(0, percent1 + percent2 / 2, f'{value2}', ha='center', va='center', fontsize=12, color='white')
|
|
97
|
+
|
|
98
|
+
# Legend and title
|
|
99
|
+
ax.legend(['Supported proteins', 'Un-supported proteins'], loc='upper left', bbox_to_anchor=(1.6, 1))
|
|
100
|
+
ax.set_title('Percentage of supported and un-supported proteins', fontsize=12)
|
|
101
|
+
|
|
102
|
+
# Formatting
|
|
103
|
+
ax.set_xlim(-0.5, 0.5)
|
|
104
|
+
ax.set_ylim(0, 100)
|
|
105
|
+
ax.axis('off')
|
|
106
|
+
|
|
107
|
+
plt.tight_layout()
|
|
108
|
+
plt.savefig(output_dir / 'Supported_and_unsupported_proteins.png', bbox_inches='tight')
|
|
109
|
+
plt.close()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def plot_protein_metrics(df, output_dir):
|
|
114
|
+
|
|
115
|
+
# 1. Protein length distribution
|
|
116
|
+
plt.figure(figsize=(8, 5))
|
|
117
|
+
plt.hist(df['protein_length'], bins=50, color='skyblue', edgecolor='black')
|
|
118
|
+
plt.title('Protein Length Distribution')
|
|
119
|
+
plt.xlabel('Protein Length')
|
|
120
|
+
plt.ylabel('Count')
|
|
121
|
+
plt.xlim(0, 2000)
|
|
122
|
+
plt.savefig(output_dir/ 'Protein_length_distribution.png', bbox_inches='tight')
|
|
123
|
+
plt.close()
|
|
124
|
+
|
|
125
|
+
# 2. Splice site distribution
|
|
126
|
+
bins = list(range(0, 12)) + [float('inf')] # [0,1,2,...,11,inf]
|
|
127
|
+
labels = ['0'] + [str(i) for i in range(1, 11)] + ['>10']
|
|
128
|
+
mapped_ranges = pd.cut(df['splice_sites'], bins=bins, labels=labels, right=False)
|
|
129
|
+
mapped_counts = mapped_ranges.value_counts().sort_index()
|
|
130
|
+
plt.figure(figsize=(10, 5))
|
|
131
|
+
ax = mapped_counts.plot(kind='bar', color='green', edgecolor='black')
|
|
132
|
+
plt.title('Splice Sites Distribution')
|
|
133
|
+
plt.xlabel('Number of Splice Sites')
|
|
134
|
+
plt.ylabel('Protein Count')
|
|
135
|
+
plt.xticks(rotation=90)
|
|
136
|
+
# Add data labels
|
|
137
|
+
for i, count in enumerate(mapped_counts):
|
|
138
|
+
ax.text(i, count + 0.5, str(count), ha='center', va='bottom', fontsize=9)
|
|
139
|
+
|
|
140
|
+
plt.tight_layout()
|
|
141
|
+
plt.savefig(output_dir / 'Splice_sites_distribution.png', bbox_inches='tight')
|
|
142
|
+
plt.close()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# 3. Mapped peptides bar plot (0โ30, >30)
|
|
148
|
+
bins = [0, 1, 2] + list(range(11, 101, 10)) + [np.inf]
|
|
149
|
+
labels = ['0', '1-10'] + [f"{i}-{i+9}" for i in range(11, 100, 10)] + ['>100']
|
|
150
|
+
|
|
151
|
+
# Bin the data
|
|
152
|
+
mapped_ranges = pd.cut(df['mapped_peptides'], bins=bins, labels=labels, right=False)
|
|
153
|
+
mapped_counts = mapped_ranges.value_counts().sort_index()
|
|
154
|
+
|
|
155
|
+
# Total number of proteins
|
|
156
|
+
total_proteins = len(df)
|
|
157
|
+
|
|
158
|
+
# Plotting
|
|
159
|
+
plt.figure(figsize=(10, 5))
|
|
160
|
+
ax = mapped_counts.plot(kind='bar', color='green', edgecolor='black')
|
|
161
|
+
plt.title('Mapped Peptides Distribution (in ranges)')
|
|
162
|
+
plt.xlabel('Number of Mapped Peptides')
|
|
163
|
+
plt.ylabel('Protein Count')
|
|
164
|
+
plt.xticks(rotation=45)
|
|
165
|
+
|
|
166
|
+
# Add value labels and percentage for the first bar
|
|
167
|
+
for i, count in enumerate(mapped_counts):
|
|
168
|
+
# Add the count labels above the bar
|
|
169
|
+
ax.text(i, count + 0.5, str(count), ha='center', va='bottom', fontsize=9)
|
|
170
|
+
|
|
171
|
+
# Add percentage inside the first bar
|
|
172
|
+
if i == 0:
|
|
173
|
+
percentage = (count / total_proteins) * 100
|
|
174
|
+
ax.text(i, count / 2, f'{percentage:.2f}%', ha='center', fontsize=10, rotation=90,color='white')
|
|
175
|
+
|
|
176
|
+
plt.tight_layout()
|
|
177
|
+
plt.savefig(output_dir / 'Mapped_peptides_distribution.png', bbox_inches='tight')
|
|
178
|
+
plt.close()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# 4. protein isoforms bar plot (0โ10, >10)
|
|
186
|
+
mapped_counts_10 = df['protein_isoforms'].apply(lambda x: str(int(x)) if x <= 10 else '>10')
|
|
187
|
+
mapped_counts_10 = mapped_counts_10.value_counts().sort_index(key=lambda x: [int(i.replace('>','')) if '>' not in i else 999 for i in x])
|
|
188
|
+
plt.figure(figsize=(8, 5))
|
|
189
|
+
mapped_counts_10.plot(kind='bar', color='purple', edgecolor='black')
|
|
190
|
+
plt.title('Mapped Peptides Distribution (0โ10, >10)')
|
|
191
|
+
plt.xlabel('Number of Protein isoforms')
|
|
192
|
+
plt.ylabel('isoforms Count')
|
|
193
|
+
plt.xticks(rotation=0)
|
|
194
|
+
plt.savefig(output_dir/ 'Protein_isoforms_distribution.png', bbox_inches='tight')
|
|
195
|
+
plt.close()
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
import os
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
def run_proteomapper(protdb_path: str, peptides_path: str, output_dir):
|
|
6
|
+
# Get the directory of this Python file (assuming Perl scripts are in the same dir)
|
|
7
|
+
base_dir = os.path.dirname(os.path.abspath(__file__))
|
|
8
|
+
|
|
9
|
+
# Paths to the local Perl scripts
|
|
10
|
+
clips_path = os.path.join(base_dir, "clips.pl")
|
|
11
|
+
promast_path = os.path.join(base_dir, "promast.pl")
|
|
12
|
+
|
|
13
|
+
# Output file in the same directory as peptides
|
|
14
|
+
output_file = output_dir / "proteomapper.tsv"
|
|
15
|
+
# output_file = peptides_path.with_suffix(".proteomapper.tsv")
|
|
16
|
+
|
|
17
|
+
# Run clips.pl
|
|
18
|
+
clips_cmd = ["perl", clips_path, "-f", protdb_path]
|
|
19
|
+
clips_result = subprocess.run(clips_cmd, capture_output=True, text=True)
|
|
20
|
+
|
|
21
|
+
if clips_result.returncode != 0:
|
|
22
|
+
raise RuntimeError(f"clips.pl failed:\n{clips_result.stderr}")
|
|
23
|
+
|
|
24
|
+
# Run promast.pl
|
|
25
|
+
promast_cmd = f"perl {promast_path} {protdb_path} {peptides_path} > {output_file}"
|
|
26
|
+
promast_result = subprocess.run(promast_cmd, shell=True, capture_output=True, text=True)
|
|
27
|
+
|
|
28
|
+
if promast_result.returncode != 0:
|
|
29
|
+
raise RuntimeError(f"promast.pl failed:\n{promast_result.stderr}")
|
|
30
|
+
|
|
31
|
+
pep_idx_file = str(protdb_path) +'.pep.idx'
|
|
32
|
+
if os.path.exists(pep_idx_file):
|
|
33
|
+
os.remove(pep_idx_file)
|
|
34
|
+
return output_file
|
|
35
|
+
|
|
36
|
+
def run_psauron(protdb_path: Path, output_dir):
|
|
37
|
+
# output_file = protdb_path.with_suffix(".psauron.csv")
|
|
38
|
+
output_file = output_dir / "psauron.csv"
|
|
39
|
+
|
|
40
|
+
command = [
|
|
41
|
+
"psauron",
|
|
42
|
+
"-i", str(protdb_path),
|
|
43
|
+
"-o", str(output_file),
|
|
44
|
+
"-p"
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
psauron_result = subprocess.run(command, capture_output=True, text=True)
|
|
48
|
+
|
|
49
|
+
if psauron_result.returncode != 0:
|
|
50
|
+
raise RuntimeError(f"psauron failed:\n{psauron_result.stderr}")
|
|
51
|
+
|
|
52
|
+
print("STDOUT:\n", psauron_result.stdout)
|
|
53
|
+
print("STDERR:\n", psauron_result.stderr)
|
|
54
|
+
|
|
55
|
+
return output_file
|
|
56
|
+
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import re
|
|
3
|
+
from Bio.Seq import Seq
|
|
4
|
+
from Bio import SeqIO
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
def df_with_genes(df):
|
|
8
|
+
df = df[df['Type'] == 'CDS'].copy() # Ensure you're working on a copy to avoid SettingWithCopyWarning
|
|
9
|
+
gene_ids = []
|
|
10
|
+
for _, row in df.iterrows():
|
|
11
|
+
string = row['Suppl']
|
|
12
|
+
if row['Source'] in [
|
|
13
|
+
'EMBL', 'EVM', 'EuGene', 'Helixer', 'BMAPv1', 'phytozome8_0', 'phytozome9_0',
|
|
14
|
+
'phytozomev10', 'phytozomev11', 'phytozomev12', 'phytozomev13', 'Gmove', 'maker',
|
|
15
|
+
'PCPHybridSetV1', 'Psat_v1a', 'juglans_regia'
|
|
16
|
+
]:
|
|
17
|
+
extracted_id = extract_id(string, r'Parent=([^;]+)')
|
|
18
|
+
else:
|
|
19
|
+
extracted_id = extract_id(string, r'transcript_id "([^"]+)"')
|
|
20
|
+
gene_ids.append(extracted_id)
|
|
21
|
+
df['Genes'] = gene_ids
|
|
22
|
+
return df
|
|
23
|
+
|
|
24
|
+
def extract_id(string, pattern):
|
|
25
|
+
match = re.search(pattern, string)
|
|
26
|
+
if match:
|
|
27
|
+
return match.group(1)
|
|
28
|
+
return "unknown_id" # Return a default value if pattern not found
|
|
29
|
+
|
|
30
|
+
def add_seqs(input_genome_path, input_gtf_path):
|
|
31
|
+
column_names = ['Seqid', 'Source', 'Type', 'Start', 'End', 'Score', 'Strand', 'Frame', 'Suppl']
|
|
32
|
+
df = pd.read_csv(input_gtf_path, sep='\t', header=None, names=column_names, dtype={'Start': int, 'End': int})
|
|
33
|
+
df['Seq'] = ""
|
|
34
|
+
df['Frame'] = df['Frame'].replace('.', 0).astype(int) # Replace '.' and convert to int
|
|
35
|
+
|
|
36
|
+
genome_sequences = SeqIO.to_dict(SeqIO.parse(input_genome_path, "fasta"))
|
|
37
|
+
|
|
38
|
+
for index, row in df.iterrows():
|
|
39
|
+
seqid = row['Seqid']
|
|
40
|
+
start = row['Start'] - 1
|
|
41
|
+
end = row['End']
|
|
42
|
+
try:
|
|
43
|
+
seq = str(genome_sequences[seqid].seq[start:end])
|
|
44
|
+
df.at[index, 'Seq'] = seq
|
|
45
|
+
except KeyError:
|
|
46
|
+
print(f"Warning: sequence ID '{seqid}' not found in genome.") # Optional: warning message
|
|
47
|
+
continue
|
|
48
|
+
return df
|
|
49
|
+
|
|
50
|
+
def get_proteins_from_cds_gtf(input_genome_path, input_gtf_path):
|
|
51
|
+
df = add_seqs(input_genome_path, input_gtf_path)
|
|
52
|
+
df_genes = df_with_genes(df)
|
|
53
|
+
df_groups = df_genes.groupby('Genes')
|
|
54
|
+
|
|
55
|
+
output_path = input_gtf_path.with_suffix('.faa')
|
|
56
|
+
|
|
57
|
+
with open(output_path, 'w') as out_f:
|
|
58
|
+
for name, sub_df in df_groups:
|
|
59
|
+
df_cds = sub_df[sub_df['Type'] == 'CDS']
|
|
60
|
+
if df_cds.empty:
|
|
61
|
+
continue
|
|
62
|
+
|
|
63
|
+
strand = sub_df['Strand'].iloc[0]
|
|
64
|
+
df_cds = df_cds.sort_values('Start')
|
|
65
|
+
cds_regions = [(int(row['Start']), int(row['End'])) for _, row in df_cds.iterrows()]
|
|
66
|
+
cds_regions.sort(key=lambda x: x[0])
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
gene = ''.join(df_cds['Seq'].tolist()).replace(' ', '')
|
|
70
|
+
except TypeError:
|
|
71
|
+
gene = 'TAANNNTTANNNNNNNNNTTANNNTAA'
|
|
72
|
+
|
|
73
|
+
first_frame = df_cds['Frame'].iloc[0] if strand == '+' else df_cds['Frame'].iloc[-1]
|
|
74
|
+
frame_offset = int(first_frame) if isinstance(first_frame, int) else 0
|
|
75
|
+
|
|
76
|
+
if strand == '-':
|
|
77
|
+
gene = str(Seq(gene).reverse_complement())
|
|
78
|
+
|
|
79
|
+
gene = gene[frame_offset:]
|
|
80
|
+
|
|
81
|
+
if len(gene) % 3 != 0:
|
|
82
|
+
gene = gene[:len(gene) - (len(gene) % 3)]
|
|
83
|
+
|
|
84
|
+
protein = str(Seq(gene).translate(to_stop=False))
|
|
85
|
+
|
|
86
|
+
out_f.write(f'>{name}\n{protein}\n')
|
|
87
|
+
|
|
88
|
+
check_abnormal_amino_acids(output_path)
|
|
89
|
+
return output_path
|
|
90
|
+
|
|
91
|
+
def check_abnormal_amino_acids(fasta_file):
|
|
92
|
+
count = 0
|
|
93
|
+
valid_amino_acids = set("ACDEFGHIKLMNPQRSTVWYX")
|
|
94
|
+
abnormal_sequences = {}
|
|
95
|
+
|
|
96
|
+
for record in SeqIO.parse(fasta_file, "fasta"):
|
|
97
|
+
sequence = str(record.seq).rstrip("*") # Avoid slicing, just remove the last '*'
|
|
98
|
+
abnormal_amino_acids = set(sequence) - valid_amino_acids
|
|
99
|
+
|
|
100
|
+
if abnormal_amino_acids:
|
|
101
|
+
count += 1
|
|
102
|
+
abnormal_sequences[record.id] = abnormal_amino_acids
|
|
103
|
+
|
|
104
|
+
if abnormal_sequences:
|
|
105
|
+
print(f"Number of sequences with abnormal amino acids = {count}")
|
|
106
|
+
print("Sequences with abnormal amino acids are:")
|
|
107
|
+
for seq_id, amino_acids in abnormal_sequences.items():
|
|
108
|
+
print(f"ID: {seq_id}, Abnormal Amino Acids: {', '.join(amino_acids)}")
|
|
109
|
+
else:
|
|
110
|
+
print("All sequences are normal.")
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gapms
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: GAP-MS is a pipeline designed to evaluate and refine predicted gene models by integrating proteogenomic evidence from mass spectrometry with in-silico gene predictions.
|
|
5
|
+
Author-email: Qussai Abbas <qussai.abbas@tum.de>
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: perl-xml-parser; platform_system == "Linux"
|
|
10
|
+
Requires-Dist: perl-xml-twig; platform_system == "Linux"
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# GAP-MS: **Gene Model Assessment using Peptides from Mass Spectrometry**
|
|
14
|
+
|
|
15
|
+
**GAP-MS** is a pipeline designed to evaluate and refine predicted gene models by integrating proteogenomic evidence from mass spectrometry with in-silico gene predictions. This approach leverages an iterative machine learning framework to classify predicted proteins as *supported* or *unsupported*, improving both specificity and overall accuracy of gene models.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## ๐ฆ Installation
|
|
20
|
+
|
|
21
|
+
We recommend setting up a dedicated Conda environment to manage dependencies:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
conda create -n gapms_env python=3.10 perl-xml-parser perl-xml-twig -c conda-forge
|
|
25
|
+
conda activate gapms_env
|
|
26
|
+
git clone https://github.com/qussai96/GAP-MS.git
|
|
27
|
+
cd GAP-MS
|
|
28
|
+
pip install -e .
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## ๐ Required Inputs
|
|
34
|
+
|
|
35
|
+
To run GAP-MS, you need the following input files:
|
|
36
|
+
|
|
37
|
+
1. **Gene models** in GTF or GFF format
|
|
38
|
+
2. **Translated protein sequences** (FASTA format) of the gene models
|
|
39
|
+
3. **Peptide list** plain text (.txt) file containing peptides identified from a mass spectrometry experiment [Each peptide should be on a separate line]
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## ๐งช Running the Pipeline
|
|
43
|
+
|
|
44
|
+
### Option 1: With translated protein FASTA file
|
|
45
|
+
|
|
46
|
+
If you already have the translated gene models in FASTA format:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
gapms -g annotations.gtf -a proteins.fasta -p peptides.txt [-o /path/to/output_directory]
|
|
50
|
+
```
|
|
51
|
+
> โน๏ธ **Note**: If the `-o` output directory is not specified, the results will be written to a folder named `GAPMS_Output` in the same directory as the GTF file.
|
|
52
|
+
|
|
53
|
+
### Option 2: With genome assembly file
|
|
54
|
+
|
|
55
|
+
If you only have the genome assembly (FASTA) and not the translated proteins, gapms will get the translated proteins from the assembly by running:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
gapms -g annotations.gtf -a assembly.fasta -p peptides.txt [-o /path/to/output_directory]
|
|
59
|
+
```
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## ๐ Optional: Use Custom Mapping File
|
|
63
|
+
|
|
64
|
+
If you prefer to use a custom peptide-to-protein mapping (instead of running `proteomapper`), use the `-m` option:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
gapms -g annotations.gtf -a assembly.fasta -m /path/to/mapping_file.tsv [-o /path/to/output_directory]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- The mapping file **must** include at least:
|
|
71
|
+
- `peptide`
|
|
72
|
+
- `protein` columns
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## ๐ Example Data
|
|
77
|
+
|
|
78
|
+
You can find examples of input files in the `tutorials/` directory to help you get started.
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## ๐ฌ Feedback & Issues
|
|
83
|
+
|
|
84
|
+
If you encounter bugs or have suggestions, please open an issue on the [GitHub repository](https://github.com/qussai96/GAP-MS/issues).
|
|
85
|
+
|
|
86
|
+
---
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
setup.py
|
|
5
|
+
gapms/__init__.py
|
|
6
|
+
gapms/extract.py
|
|
7
|
+
gapms/filter.py
|
|
8
|
+
gapms/gtf_utils.py
|
|
9
|
+
gapms/main.py
|
|
10
|
+
gapms/mapping_utils.py
|
|
11
|
+
gapms/model_utils.py
|
|
12
|
+
gapms/peptide_utils.py
|
|
13
|
+
gapms/plotting.py
|
|
14
|
+
gapms/tools.py
|
|
15
|
+
gapms/translate.py
|
|
16
|
+
gapms.egg-info/PKG-INFO
|
|
17
|
+
gapms.egg-info/SOURCES.txt
|
|
18
|
+
gapms.egg-info/dependency_links.txt
|
|
19
|
+
gapms.egg-info/requires.txt
|
|
20
|
+
gapms.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gapms
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "gapms"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "GAP-MS is a pipeline designed to evaluate and refine predicted gene models by integrating proteogenomic evidence from mass spectrometry with in-silico gene predictions."
|
|
9
|
+
authors = [{ name = "Qussai Abbas", email = "qussai.abbas@tum.de" }]
|
|
10
|
+
dependencies = [
|
|
11
|
+
"perl-xml-parser; platform_system=='Linux'",
|
|
12
|
+
"perl-xml-twig; platform_system=='Linux'",
|
|
13
|
+
]
|
|
14
|
+
readme = "README.md"
|
|
15
|
+
requires-python = ">=3.10"
|
gapms-0.1.0/setup.cfg
ADDED
gapms-0.1.0/setup.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from setuptools import setup, find_packages
|
|
2
|
+
|
|
3
|
+
setup(
|
|
4
|
+
name='gapms',
|
|
5
|
+
version='0.1.0',
|
|
6
|
+
packages=find_packages(),
|
|
7
|
+
install_requires=[
|
|
8
|
+
'pandas',
|
|
9
|
+
'numpy',
|
|
10
|
+
'biopython',
|
|
11
|
+
'matplotlib',
|
|
12
|
+
'seaborn',
|
|
13
|
+
'scipy',
|
|
14
|
+
'scikit-learn',
|
|
15
|
+
'xgboost',
|
|
16
|
+
'shap',
|
|
17
|
+
'psauron',
|
|
18
|
+
],
|
|
19
|
+
entry_points={
|
|
20
|
+
'console_scripts': [
|
|
21
|
+
'gapms=gapms.main:main',
|
|
22
|
+
],
|
|
23
|
+
},
|
|
24
|
+
)
|