promb 1.0.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.
promb-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright © 2025 Merck & Co., Inc., Rahway, NJ, USA and its affiliates. All rights reserved.
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
13
+ all 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
21
+ THE SOFTWARE.
@@ -0,0 +1,12 @@
1
+ Name Version License
2
+ XlsxWriter 3.2.3 BSD License
3
+ numpy 2.2.4 BSD License
4
+ pandas 2.2.3 BSD License
5
+ promb 1.0.0 MIT
6
+ python-dateutil 2.9.0.post0 Apache Software License; BSD License
7
+ pytz 2025.2 MIT License
8
+ scipy 1.15.2 BSD License
9
+ six 1.17.0 MIT License
10
+ tqdm 4.67.1 MIT License; Mozilla Public License 2.0 (MPL 2.0)
11
+ tzdata 2025.2 Apache Software License
12
+
@@ -0,0 +1,12 @@
1
+ recursive-include promb/ *.py *.txt.gz *.fasta.gz
2
+ include LICENSE
3
+ include requirements.txt
4
+
5
+ global-exclude *.pyc
6
+ global-exclude *.pyo
7
+ global-exclude .git
8
+ global-exclude .DS_Store
9
+ global-exclude .ipynb_checkpoints
10
+
11
+ prune tests
12
+ prune work
promb-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: promb
3
+ Version: 1.0.0
4
+ Summary: promb: protein mutation burden
5
+ Home-page: https://github.com/MSDLLCPapers/promb
6
+ Author: David Prihoda
7
+ Author-email: david.prihoda@gmail.com
8
+ License: MIT
9
+ Keywords: antibody humanness,de-novo humanness,human peptide content,oasis,biophi,mutation burden,promb
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ License-File: LICENSES_THIRD_PARTY
15
+ Requires-Dist: scipy
16
+ Requires-Dist: pandas
17
+ Requires-Dist: tqdm
18
+ Dynamic: author
19
+ Dynamic: author-email
20
+ Dynamic: classifier
21
+ Dynamic: description
22
+ Dynamic: description-content-type
23
+ Dynamic: home-page
24
+ Dynamic: keywords
25
+ Dynamic: license
26
+ Dynamic: license-file
27
+ Dynamic: requires-dist
28
+ Dynamic: requires-python
29
+ Dynamic: summary
30
+
31
+ # promb: protein humanness evaluation toolkit
32
+
33
+ ```
34
+ * █
35
+ ▄▄▄▄ ▄▄▄ ▄█▄ ▄▄▄▄ █▄▄▄
36
+ █ █ █ █▓███ █ █ █ █ █
37
+ █▄▄▄▀ █ ▀███▀ █ █ █▄▄▄▀
38
+ █
39
+ ▀ protein mutation burden
40
+
41
+ # 1 2 3 4 5 6
42
+ # CVQLQQSGA VQLQQSGAE QLQQSGAEL LQQSGAELA QQSGAELAR QSGAELARP queries
43
+ # QVQLQQSGP VQLMQSGAE QLMQSGAEV LHQSGSELA QQSGSELAL PSAAELARP hits
44
+ # ^ ^ ^ ^ + ^ + + ^ ^ ^
45
+ ```
46
+
47
+ <p>
48
+ <a href="https://pypi.org/project/promb/">
49
+ <img src="https://img.shields.io/pypi/dm/promb"
50
+ alt="Pip Install"></a>
51
+ <a href="https://github.com/MSDLLCPapers/promb/releases">
52
+ <img src="https://img.shields.io/pypi/v/promb"
53
+ alt="Latest release"></a>
54
+ </p>
55
+
56
+ Python library for computing protein humanness (or mouse-ness, dog-ness, cow-ness, ...) based on average number of mutations
57
+ to nearest peptide in a reference proteome (Human SwissProt, human antibody repertoires in OAS, or a custom reference DB).
58
+
59
+ ## How does this work? What is protein humanness?
60
+
61
+ A database of human peptides (or other reference proteome) is loaded in-memory into a big python set for fast lookups.
62
+ Near matches are found using an optimized lookup strategy implemented with `cdist` function in `scipy`.
63
+
64
+ Human SwissProt and Human OAS are stored as part of this package.
65
+ A custom reference DB can be provided as a gzipped fasta or text file.
66
+
67
+ > [!NOTE]
68
+ > More human doesn't always mean "good". Peptides like "GGGGGGGGG" or "EKEKEKEKE" are human but you don't necessarily want your protein to contain those. Make sure to check for sequence entropy, AlphaFold2 confidence, or other quality metrics.
69
+
70
+
71
+ ## Usage
72
+
73
+ Install using pip:
74
+
75
+ ```bash
76
+ pip install promb
77
+ ```
78
+
79
+ ### Command-line interface
80
+
81
+ Check which peptides in a sequence are present in the DB (exact match, very fast):
82
+
83
+ ```bash
84
+ # FASTA file(s)
85
+ promb exact -d human-reference -l 9 -o output_matches.csv query.fasta
86
+ # PDB file(s)
87
+ promb exact -d human-reference -l 9 -o output_matches.csv --chain A ./pdb_directory/
88
+ # Output:
89
+ # File,ID,Position,Peptide,Found
90
+ # test_antibody.fa,Pembrolizumab,1,EIVLTQSPA,True
91
+ # test_antibody.fa,Pembrolizumab,2,IVLTQSPAT,True
92
+ # test_antibody.fa,Pembrolizumab,3,VLTQSPATL,True
93
+
94
+ ```
95
+
96
+ Find nearest human peptides (a lot slower than exact match search). Peptides are ranked by identity (number of mutations), ties are resolved by BLOSUM similarity. The search is exhaustive - we don't use any pre-filtering step, all peptides from reference database are compared to the query.
97
+
98
+ ```bash
99
+ # FASTA file(s)
100
+ promb nearest -d human-reference -l 9 -o output_matches.csv query.fasta
101
+ # PDB file(s)
102
+ promb nearest -d human-reference -l 9 -o output_matches.csv --chain A ./pdb_directory/
103
+ # Output:
104
+ # File,ID,Position,Peptide,Nearest,Mutations
105
+ # test_antibody.fa,Pembrolizumab,1,EIVLTQSPA,EIVLTQSPA,0
106
+ # test_antibody.fa,Pembrolizumab,2,IVLTQSPAT,IVLTQSPAT,0
107
+ # test_antibody.fa,Pembrolizumab,3,VLTQSPATL,VLTQSPATL,0
108
+ ```
109
+
110
+ You can use promb for very fast computation of the OASis antibody humanness score from BioPhi:
111
+
112
+ ```bash
113
+ # FASTA file(s)
114
+ promb oasis -o output_scores.csv ./input/sequences/
115
+ # Output:
116
+ # File,ID,Identity
117
+ # test_antibody.fa,Pembrolizumab,0.7572815533980582
118
+ # test_antibody.fa,Pembrolizumab,0.7142857142857143
119
+ ```
120
+
121
+ ### Python library
122
+
123
+ First, initialize the in-memory peptide database using `init_db`:
124
+
125
+ ```python
126
+ from promb import init_db
127
+ # Use pre-defined Human reference proteome (UP000005640)
128
+ db = init_db('human-reference', 9)
129
+ # Use pre-defined Human SwissProt DB
130
+ db = init_db('human-swissprot', 9)
131
+ # Use pre-defined Human OAS DB (antibody peptides found in >=10% of subjects)
132
+ db = init_db('human-oas')
133
+ # Use custom path with gzipped fasta file
134
+ db = init_db('path/to/db.fasta.gz', 9)
135
+ # Use custom path with gzipped text file, one peptide per line
136
+ db = init_db('path/to/db.txt.gz')
137
+ ```
138
+
139
+ Check which peptides in a sequence are present in the DB (exact match, very fast):
140
+
141
+ ```python
142
+ from promb import init_db
143
+
144
+ db = init_db('human-oas')
145
+
146
+ db.contains('HWGRRKAWC')
147
+ # True
148
+ db.contains('MGPLHQFLL')
149
+ # False
150
+
151
+ # Use 'compute_peptide_content' to compute OASis-like score (% of peptides that are human, exact match)
152
+ db.compute_peptide_content('QVQLVQSGVEVKKPGASVKVSCKASGYTFTNYYMYWVRQAPGQGLEWMGGINPSNGGTNFNEKFKNRVTLTTDSSTTTAYMELKSLQFDDTAVYYCARRDYRFDMGFDYWGQGTTVTVSS')
153
+ # 0.7142857142857143
154
+ ```
155
+
156
+ Find nearest human peptides (a lot slower than exact match search). Peptides are ranked by identity (number of mutations), ties are resolved by BLOSUM similarity. The search is exhaustive - we don't use any pre-filtering step, all peptides from reference database are compared to the query.
157
+
158
+ ```python
159
+ from promb import init_db, print_nearest
160
+
161
+ db = init_db('human-reference', 9)
162
+
163
+ peptides = db.chop_seq_peptides('CVQLQQSGAELARPPASVKMSCKAS')
164
+ # ['CVQLQQSGA', 'VQLQQSGAE', 'QLQQSGAEL', ...]
165
+ nearest = db.find_nearest_peptides(peptides, 1)
166
+ # [['QVQLQQSGP'], ['VQLMQSGAE'], ['QLMQSGAEV'], ...]
167
+
168
+ print_nearest(peptides, nearest)
169
+ # ^ = mutation, + = similar residue
170
+ #
171
+ # 1 2 3 4 5 6 7 8 9 10
172
+ # CVQLQQSGA VQLQQSGAE QLQQSGAEL LQQSGAELA QQSGAELAR QSGAELARP SGAELARPP GAELARPPA AELARPPAS ELARPPASV queries
173
+ # QVQLQQSGP VQLMQSGAE QLMQSGAEV LHQSGSELA QQSGSELAL PSAAELARP SGAELRQPP GAELLEPPA LELQRPPAS ELQRPPAST hits
174
+ # ^ ^ ^ ^ + ^ + + ^ ^ ^ ^+ ^^ ^ ^ ^ ^
175
+
176
+ # 11 12 13 14 15 16 17
177
+ # LARPPASVK ARPPASVKM RPPASVKMS PPASVKMSC PASVKMSCK ASVKMSCKA SVKMSCKAS queries
178
+ # LAMPPASVK AMPPASVKV RPPASVGMS PPASYKSSC VASTKMSCK ASVKVSCKA SVKVSCKAS hits
179
+ # ^ ^ + ^ ^ ^ ^ ^ + +
180
+
181
+ ```
182
+
183
+ Compute protein mutation burden (PMB) = average number of non-human mutations per peptide:
184
+
185
+ ```python
186
+ pmb = db.compute_pmb('CVQLQQSGAELARPPASVKMSCKAS')
187
+ pmb
188
+ # 1.176 mutations per peptide
189
+ ```
190
+
191
+ PMB is slow for peptides with more than 2 mutations, you can cap the number of mutations per peptide to speed up computation:
192
+
193
+ ```python
194
+ pmb = db.compute_pmb('ELVISISALIVE', max=3)
195
+ pmb
196
+ # 2.75 mutations per peptide (capped at 3 - peptides with more mutations will be counted as 3 mutations)
197
+ ```
198
+
199
+ ## Acknowledgements
200
+
201
+ Promb is building upon our previous work - OASis antibody humanness metric:
202
+
203
+ > David Prihoda, Jad Maamary, Andrew Waight, Veronica Juan, Laurence Fayadat-Dilman, Daniel Svozil & Danny A. Bitton (2022)
204
+ > BioPhi: A platform for antibody design, humanization, and humanness evaluation based on natural antibody repertoires and deep learning, mAbs, 14:1, DOI: https://doi.org/10.1080/19420862.2021.2020203
205
+
206
+ OASis is based on antibody repertoires from the Observed Antibody Space:
207
+
208
+ > Kovaltsuk, A., Leem, J., Kelm, S., Snowden, J., Deane, C. M., & Krawczyk, K. (2018). Observed Antibody Space: A Resource for Data Mining Next-Generation Sequencing of Antibody Repertoires. The Journal of Immunology, 201(8), 2502–2509. https://doi.org/10.4049/jimmunol.1800708
promb-1.0.0/README.md ADDED
@@ -0,0 +1,178 @@
1
+ # promb: protein humanness evaluation toolkit
2
+
3
+ ```
4
+ * █
5
+ ▄▄▄▄ ▄▄▄ ▄█▄ ▄▄▄▄ █▄▄▄
6
+ █ █ █ █▓███ █ █ █ █ █
7
+ █▄▄▄▀ █ ▀███▀ █ █ █▄▄▄▀
8
+ █
9
+ ▀ protein mutation burden
10
+
11
+ # 1 2 3 4 5 6
12
+ # CVQLQQSGA VQLQQSGAE QLQQSGAEL LQQSGAELA QQSGAELAR QSGAELARP queries
13
+ # QVQLQQSGP VQLMQSGAE QLMQSGAEV LHQSGSELA QQSGSELAL PSAAELARP hits
14
+ # ^ ^ ^ ^ + ^ + + ^ ^ ^
15
+ ```
16
+
17
+ <p>
18
+ <a href="https://pypi.org/project/promb/">
19
+ <img src="https://img.shields.io/pypi/dm/promb"
20
+ alt="Pip Install"></a>
21
+ <a href="https://github.com/MSDLLCPapers/promb/releases">
22
+ <img src="https://img.shields.io/pypi/v/promb"
23
+ alt="Latest release"></a>
24
+ </p>
25
+
26
+ Python library for computing protein humanness (or mouse-ness, dog-ness, cow-ness, ...) based on average number of mutations
27
+ to nearest peptide in a reference proteome (Human SwissProt, human antibody repertoires in OAS, or a custom reference DB).
28
+
29
+ ## How does this work? What is protein humanness?
30
+
31
+ A database of human peptides (or other reference proteome) is loaded in-memory into a big python set for fast lookups.
32
+ Near matches are found using an optimized lookup strategy implemented with `cdist` function in `scipy`.
33
+
34
+ Human SwissProt and Human OAS are stored as part of this package.
35
+ A custom reference DB can be provided as a gzipped fasta or text file.
36
+
37
+ > [!NOTE]
38
+ > More human doesn't always mean "good". Peptides like "GGGGGGGGG" or "EKEKEKEKE" are human but you don't necessarily want your protein to contain those. Make sure to check for sequence entropy, AlphaFold2 confidence, or other quality metrics.
39
+
40
+
41
+ ## Usage
42
+
43
+ Install using pip:
44
+
45
+ ```bash
46
+ pip install promb
47
+ ```
48
+
49
+ ### Command-line interface
50
+
51
+ Check which peptides in a sequence are present in the DB (exact match, very fast):
52
+
53
+ ```bash
54
+ # FASTA file(s)
55
+ promb exact -d human-reference -l 9 -o output_matches.csv query.fasta
56
+ # PDB file(s)
57
+ promb exact -d human-reference -l 9 -o output_matches.csv --chain A ./pdb_directory/
58
+ # Output:
59
+ # File,ID,Position,Peptide,Found
60
+ # test_antibody.fa,Pembrolizumab,1,EIVLTQSPA,True
61
+ # test_antibody.fa,Pembrolizumab,2,IVLTQSPAT,True
62
+ # test_antibody.fa,Pembrolizumab,3,VLTQSPATL,True
63
+
64
+ ```
65
+
66
+ Find nearest human peptides (a lot slower than exact match search). Peptides are ranked by identity (number of mutations), ties are resolved by BLOSUM similarity. The search is exhaustive - we don't use any pre-filtering step, all peptides from reference database are compared to the query.
67
+
68
+ ```bash
69
+ # FASTA file(s)
70
+ promb nearest -d human-reference -l 9 -o output_matches.csv query.fasta
71
+ # PDB file(s)
72
+ promb nearest -d human-reference -l 9 -o output_matches.csv --chain A ./pdb_directory/
73
+ # Output:
74
+ # File,ID,Position,Peptide,Nearest,Mutations
75
+ # test_antibody.fa,Pembrolizumab,1,EIVLTQSPA,EIVLTQSPA,0
76
+ # test_antibody.fa,Pembrolizumab,2,IVLTQSPAT,IVLTQSPAT,0
77
+ # test_antibody.fa,Pembrolizumab,3,VLTQSPATL,VLTQSPATL,0
78
+ ```
79
+
80
+ You can use promb for very fast computation of the OASis antibody humanness score from BioPhi:
81
+
82
+ ```bash
83
+ # FASTA file(s)
84
+ promb oasis -o output_scores.csv ./input/sequences/
85
+ # Output:
86
+ # File,ID,Identity
87
+ # test_antibody.fa,Pembrolizumab,0.7572815533980582
88
+ # test_antibody.fa,Pembrolizumab,0.7142857142857143
89
+ ```
90
+
91
+ ### Python library
92
+
93
+ First, initialize the in-memory peptide database using `init_db`:
94
+
95
+ ```python
96
+ from promb import init_db
97
+ # Use pre-defined Human reference proteome (UP000005640)
98
+ db = init_db('human-reference', 9)
99
+ # Use pre-defined Human SwissProt DB
100
+ db = init_db('human-swissprot', 9)
101
+ # Use pre-defined Human OAS DB (antibody peptides found in >=10% of subjects)
102
+ db = init_db('human-oas')
103
+ # Use custom path with gzipped fasta file
104
+ db = init_db('path/to/db.fasta.gz', 9)
105
+ # Use custom path with gzipped text file, one peptide per line
106
+ db = init_db('path/to/db.txt.gz')
107
+ ```
108
+
109
+ Check which peptides in a sequence are present in the DB (exact match, very fast):
110
+
111
+ ```python
112
+ from promb import init_db
113
+
114
+ db = init_db('human-oas')
115
+
116
+ db.contains('HWGRRKAWC')
117
+ # True
118
+ db.contains('MGPLHQFLL')
119
+ # False
120
+
121
+ # Use 'compute_peptide_content' to compute OASis-like score (% of peptides that are human, exact match)
122
+ db.compute_peptide_content('QVQLVQSGVEVKKPGASVKVSCKASGYTFTNYYMYWVRQAPGQGLEWMGGINPSNGGTNFNEKFKNRVTLTTDSSTTTAYMELKSLQFDDTAVYYCARRDYRFDMGFDYWGQGTTVTVSS')
123
+ # 0.7142857142857143
124
+ ```
125
+
126
+ Find nearest human peptides (a lot slower than exact match search). Peptides are ranked by identity (number of mutations), ties are resolved by BLOSUM similarity. The search is exhaustive - we don't use any pre-filtering step, all peptides from reference database are compared to the query.
127
+
128
+ ```python
129
+ from promb import init_db, print_nearest
130
+
131
+ db = init_db('human-reference', 9)
132
+
133
+ peptides = db.chop_seq_peptides('CVQLQQSGAELARPPASVKMSCKAS')
134
+ # ['CVQLQQSGA', 'VQLQQSGAE', 'QLQQSGAEL', ...]
135
+ nearest = db.find_nearest_peptides(peptides, 1)
136
+ # [['QVQLQQSGP'], ['VQLMQSGAE'], ['QLMQSGAEV'], ...]
137
+
138
+ print_nearest(peptides, nearest)
139
+ # ^ = mutation, + = similar residue
140
+ #
141
+ # 1 2 3 4 5 6 7 8 9 10
142
+ # CVQLQQSGA VQLQQSGAE QLQQSGAEL LQQSGAELA QQSGAELAR QSGAELARP SGAELARPP GAELARPPA AELARPPAS ELARPPASV queries
143
+ # QVQLQQSGP VQLMQSGAE QLMQSGAEV LHQSGSELA QQSGSELAL PSAAELARP SGAELRQPP GAELLEPPA LELQRPPAS ELQRPPAST hits
144
+ # ^ ^ ^ ^ + ^ + + ^ ^ ^ ^+ ^^ ^ ^ ^ ^
145
+
146
+ # 11 12 13 14 15 16 17
147
+ # LARPPASVK ARPPASVKM RPPASVKMS PPASVKMSC PASVKMSCK ASVKMSCKA SVKMSCKAS queries
148
+ # LAMPPASVK AMPPASVKV RPPASVGMS PPASYKSSC VASTKMSCK ASVKVSCKA SVKVSCKAS hits
149
+ # ^ ^ + ^ ^ ^ ^ ^ + +
150
+
151
+ ```
152
+
153
+ Compute protein mutation burden (PMB) = average number of non-human mutations per peptide:
154
+
155
+ ```python
156
+ pmb = db.compute_pmb('CVQLQQSGAELARPPASVKMSCKAS')
157
+ pmb
158
+ # 1.176 mutations per peptide
159
+ ```
160
+
161
+ PMB is slow for peptides with more than 2 mutations, you can cap the number of mutations per peptide to speed up computation:
162
+
163
+ ```python
164
+ pmb = db.compute_pmb('ELVISISALIVE', max=3)
165
+ pmb
166
+ # 2.75 mutations per peptide (capped at 3 - peptides with more mutations will be counted as 3 mutations)
167
+ ```
168
+
169
+ ## Acknowledgements
170
+
171
+ Promb is building upon our previous work - OASis antibody humanness metric:
172
+
173
+ > David Prihoda, Jad Maamary, Andrew Waight, Veronica Juan, Laurence Fayadat-Dilman, Daniel Svozil & Danny A. Bitton (2022)
174
+ > BioPhi: A platform for antibody design, humanization, and humanness evaluation based on natural antibody repertoires and deep learning, mAbs, 14:1, DOI: https://doi.org/10.1080/19420862.2021.2020203
175
+
176
+ OASis is based on antibody repertoires from the Observed Antibody Space:
177
+
178
+ > Kovaltsuk, A., Leem, J., Kelm, S., Snowden, J., Deane, C. M., & Krawczyk, K. (2018). Observed Antibody Space: A Resource for Data Mining Next-Generation Sequencing of Antibody Repertoires. The Journal of Immunology, 201(8), 2502–2509. https://doi.org/10.4049/jimmunol.1800708
@@ -0,0 +1,7 @@
1
+ from .__version__ import __version__
2
+
3
+ from .db import init_db
4
+
5
+ from .formatting import print_nearest
6
+
7
+ from .cli import run_promb
@@ -0,0 +1 @@
1
+ __version__ = '1.0.0'
@@ -0,0 +1,218 @@
1
+ from __future__ import annotations
2
+ import argparse
3
+ import sys
4
+ import pandas as pd
5
+
6
+ from promb import init_db
7
+ from tqdm import tqdm
8
+
9
+ from promb.netmhc import predict_netmhc_top_ranks
10
+ from promb.parsing import iterate_sequences
11
+
12
+ def run_promb(
13
+ db,
14
+ input_paths,
15
+ netmhc_alleles: list[str] = None,
16
+ netmhc_peptide_lengths=None,
17
+ mode='mutations',
18
+ chains: str = None,
19
+ ):
20
+ if netmhc_peptide_lengths is None:
21
+ netmhc_peptide_lengths = [12, 13, 14, 15, 16, 17]
22
+ tuples = iterate_sequences(input_paths, chains=chains)
23
+ skipped_ids = []
24
+ dfs = []
25
+ for filename, sequence_id, sequence in tqdm(tuples):
26
+ if len(sequence) < db.peptide_length:
27
+ skipped_ids.append(sequence_id)
28
+ continue
29
+ peptides = db.chop_seq_peptides(sequence)
30
+ df = pd.DataFrame([{
31
+ 'File': filename,
32
+ 'ID': sequence_id,
33
+ 'Position': position,
34
+ 'Peptide': peptide,
35
+ } for position, peptide in enumerate(peptides, start=1)])
36
+ if mode == 'nearest':
37
+ nearest = db.find_nearest_peptides(peptides, n=1)
38
+ df['Nearest'] = [n[0] for n in nearest]
39
+ df['Mutations'] = [sum(aa != bb for aa, bb in zip(peptide, n[0])) for peptide, n in zip(peptides, nearest)]
40
+ elif mode == 'exact':
41
+ df['Found'] = [db.contains(peptide) for peptide in peptides]
42
+ elif mode == 'content':
43
+ df['Content'] = [db.contains(peptide) for peptide in peptides]
44
+ df = df.groupby(['File', 'ID'], as_index=False).agg({'Content': 'mean'})
45
+ print(df)
46
+ else:
47
+ raise ValueError(f'Unknown mode: {mode}')
48
+ if netmhc_alleles:
49
+ assert db.peptide_length == 9, 'DB needs to contain 9-mers, current implementation matches peptides to the predicted netMHCpan 9-mer core'
50
+ core_ranks, core_binders = predict_netmhc_top_ranks(sequence, k=db.peptide_length, alleles=netmhc_alleles,
51
+ peptide_lengths=netmhc_peptide_lengths)
52
+ df['Top_Rank'] = core_ranks.min(axis=1).values
53
+ assert (df['Peptide'] == core_ranks.index).all(), 'Expected the same order of peptides in df and core_ranks'
54
+ df = pd.concat([
55
+ df.reset_index(drop=True),
56
+ core_ranks.reset_index(drop=True),
57
+ core_binders.reset_index(drop=True)
58
+ ], axis=1)
59
+ dfs.append(df)
60
+ if not dfs:
61
+ raise ValueError(f'No input sequences found in: {input_paths}')
62
+ result = pd.concat(dfs)
63
+ return result, skipped_ids
64
+
65
+
66
+ def run_and_save(db_path: str, peptide_length=None, output_path=None, **kwargs):
67
+ db = init_db(db_path, peptide_length=peptide_length)
68
+ result, skipped_ids = run_promb(db=db, **kwargs)
69
+
70
+ if output_path and output_path != '-':
71
+ if output_path.endswith(('.csv', '.csv.gz')):
72
+ result.to_csv(output_path, index=False)
73
+ elif output_path.endswith('.xlsx'):
74
+ with pd.ExcelWriter(output_path, engine='xlsxwriter') as writer:
75
+ result.to_excel(writer, sheet_name='Peptides', index=False)
76
+ sheet = writer.sheets['Peptides']
77
+ header = result.columns.tolist()
78
+ id_col = header.index('ID')
79
+ sheet.set_column(id_col, id_col, 20)
80
+ peptide_col = header.index('Peptide')
81
+ sheet.set_column(peptide_col, peptide_col, db.peptide_length + 2)
82
+ # format Mutations from white (0) to red (3)
83
+ if 'Mutations' in header:
84
+ mutations_col = header.index('Mutations')
85
+ sheet.conditional_format(1, mutations_col, len(result), mutations_col, {
86
+ 'type': '2_color_scale',
87
+ 'min_type': 'num',
88
+ 'min_value': 0,
89
+ 'max_type': 'num',
90
+ 'max_value': 4,
91
+ 'min_color': '#FFFFFF',
92
+ 'max_color': '#ff7b91'
93
+ })
94
+ # format Rank columns from Dark purple (1.0) to purple (5.0) to white (20.0)
95
+ if 'Top_Rank' in header:
96
+ rank_from = header.index('Top_Rank')
97
+ rank_to = [(i, col) for i, col in enumerate(header) if col.endswith('_Rank')][-1][0]
98
+ sheet.conditional_format(1, rank_from, len(result), rank_to, {
99
+ 'type': '3_color_scale',
100
+ 'min_type': 'num',
101
+ 'min_value': 1,
102
+ 'mid_type': 'num',
103
+ 'mid_value': 5,
104
+ 'max_type': 'num',
105
+ 'max_value': 20,
106
+ 'min_color': '#c362ff',
107
+ 'mid_color': '#cb98ff',
108
+ 'max_color': '#FFFFFF'
109
+ })
110
+ elif output_path == '/dev/null':
111
+ pass
112
+ else:
113
+ raise NotImplementedError(f'Unsupported output format, expected .csv or .xlsx, got: {output_path}')
114
+ else:
115
+ result.to_csv(sys.stdout, index=False)
116
+
117
+ numeric_columns = [c for c in result.select_dtypes(include=['number', 'bool']).columns if c not in ['Position']]
118
+ for column in numeric_columns:
119
+ print(f"{column}: Statistics across sequences", file=sys.stderr)
120
+ print(result.groupby(['File', 'ID'])[column].mean().describe().T, file=sys.stderr)
121
+
122
+ if skipped_ids:
123
+ print(f"NOTE: Skipped {len(skipped_ids)} sequences because they were shorter "
124
+ f"than the peptide length ({db.peptide_length})", file=sys.stderr)
125
+ if output_path:
126
+ print("Saved to:", output_path, file=sys.stderr)
127
+
128
+
129
+ def run_oasis(input_paths, output_path=None, chains=None):
130
+ db = init_db('human-oas')
131
+ tuples = iterate_sequences(input_paths, chains=chains)
132
+
133
+ result = []
134
+ skipped_ids = []
135
+ for filename, sequence_id, sequence in tqdm(tuples):
136
+ result.append({
137
+ 'File': filename,
138
+ 'ID': sequence_id,
139
+ 'Identity': db.compute_peptide_content(sequence),
140
+ })
141
+ result = pd.DataFrame(result)
142
+
143
+ if output_path and output_path != '-':
144
+ if output_path.endswith(('.csv', '.csv.gz')):
145
+ result.to_csv(output_path, index=False)
146
+ elif output_path.endswith('.xlsx'):
147
+ with pd.ExcelWriter(output_path, engine='xlsxwriter') as writer:
148
+ result.to_excel(writer, sheet_name='Scores', index=False)
149
+ sheet = writer.sheets['Scores']
150
+ header = result.columns.tolist()
151
+ id_col = header.index('ID')
152
+ sheet.set_column(id_col, id_col, 20)
153
+ identity_col = header.index('Identity')
154
+ sheet.conditional_format(1, identity_col, len(result), identity_col, {
155
+ 'type': '2_color_scale',
156
+ 'min_type': 'num',
157
+ 'min_value': 0,
158
+ 'max_type': 'num',
159
+ 'max_value': 1,
160
+ 'min_color': '#ff7b91',
161
+ 'max_color': '#FFFFFF'
162
+ })
163
+ elif output_path == '/dev/null':
164
+ pass
165
+ else:
166
+ raise NotImplementedError(f'Unsupported output format, expected .csv or .xlsx, got: {output_path}')
167
+ else:
168
+ result.to_csv(sys.stdout, index=False)
169
+
170
+ if skipped_ids:
171
+ print(f"NOTE: Skipped {len(skipped_ids)} sequences because they were shorter "
172
+ f"than the peptide length ({db.peptide_length})", file=sys.stderr)
173
+ if output_path:
174
+ print("Saved to:", output_path, file=sys.stderr)
175
+
176
+ def main(args=None):
177
+ parser = argparse.ArgumentParser()
178
+ subparsers = parser.add_subparsers(dest='command')
179
+
180
+ nearest_parser = subparsers.add_parser('nearest')
181
+ exact_parser = subparsers.add_parser('exact')
182
+ oasis_parser = subparsers.add_parser('oasis')
183
+
184
+ for p in [nearest_parser, exact_parser, oasis_parser]:
185
+ p.add_argument('input', nargs='+', help='Input file(s) - FASTA, .txt/.txt.gz (with one peptide per line), .pdb file, or a directory of such files')
186
+ p.add_argument('-c', '--chains', help='Chains to parse when processing PDB files (comma-separated)')
187
+ p.add_argument('-o', '--output', help='Output CSV file, will print to stdout if not provided')
188
+
189
+ for p in [nearest_parser, exact_parser]:
190
+ p.add_argument('-d', '--db', required=True, help='Input database name (oas-human, oas-swissprot) or path to .txt.gz file (one peptide per line, same length) or .fasta.gz file (whole sequences in fasta format)')
191
+ p.add_argument('-l', '--peptide-length', type=int, help='Length of peptide (when using oas-swissprot or other fasta database)')
192
+ p.add_argument('-a', '--netmhc-alleles', help='Run netMHCIIpan for given alleles (comma-separated, for example DRB1_0101,DRB1_0102). '
193
+ 'requires netMHCIIpan license and netMHCIIpan to be installed and on PATH')
194
+
195
+ args = parser.parse_args(args)
196
+
197
+ if args.command is None:
198
+ parser.print_help()
199
+ if args.command == 'oasis':
200
+ run_oasis(
201
+ input_paths=args.input,
202
+ chains=args.chains,
203
+ output_path=args.output,
204
+ )
205
+ else:
206
+ run_and_save(
207
+ db_path=args.db,
208
+ input_paths=args.input,
209
+ peptide_length=args.peptide_length,
210
+ chains=args.chains,
211
+ netmhc_alleles=args.netmhc_alleles.split(',') if args.netmhc_alleles else None,
212
+ mode=args.command,
213
+ output_path=args.output,
214
+ )
215
+
216
+
217
+ if __name__ == '__main__':
218
+ main()