kprot 0.0.1__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.
kprot-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ include pyproject.toml
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
kprot-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: kprot
3
+ Version: 0.0.1
4
+ Summary: nbdev project for kprot
5
+ Author-email: sky1ove <lcai888666@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/sky1ove/kprot
8
+ Project-URL: Documentation, https://sky1ove.github.io/kprot/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: biopython>=1.87
16
+ Requires-Dist: matplotlib>=3.10.8
17
+ Requires-Dist: pandas>=2.3.3
18
+ Requires-Dist: requests>=2.33.1
19
+ Requires-Dist: scikit-learn>=1.7.2
20
+ Requires-Dist: sentencepiece>=0.2.1
21
+ Requires-Dist: torch>=2.11.0
22
+ Requires-Dist: tqdm>=4.67.3
23
+ Requires-Dist: transformers>=5.5.3
24
+ Dynamic: license-file
25
+
26
+ # kprot
27
+
28
+
29
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
30
+
31
+ This file will become your README and also the index of your
32
+ documentation.
33
+
34
+ ## Developer Guide
35
+
36
+ If you are new to using `nbdev` here are some useful pointers to get you
37
+ started.
38
+
39
+ ### Install kprot in Development mode
40
+
41
+ ``` sh
42
+ # make sure kprot package is installed in development mode
43
+ $ pip install -e .
44
+
45
+ # make changes under nbs/ directory
46
+ # ...
47
+
48
+ # compile to have changes apply to kprot
49
+ $ nbdev_prepare
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Installation
55
+
56
+ Install latest from the GitHub
57
+ [repository](https://github.com/sky1ove/kprot):
58
+
59
+ ``` sh
60
+ $ pip install git+https://github.com/sky1ove/kprot.git
61
+ ```
62
+
63
+ or from [conda](https://anaconda.org/sky1ove/kprot)
64
+
65
+ ``` sh
66
+ $ conda install -c sky1ove kprot
67
+ ```
68
+
69
+ or from [pypi](https://pypi.org/project/kprot/)
70
+
71
+ ``` sh
72
+ $ pip install kprot
73
+ ```
74
+
75
+ ### Documentation
76
+
77
+ Documentation can be found hosted on this GitHub
78
+ [repository](https://github.com/sky1ove/kprot)’s
79
+ [pages](https://sky1ove.github.io/kprot/). Additionally you can find
80
+ package manager specific guidelines on
81
+ [conda](https://anaconda.org/sky1ove/kprot) and
82
+ [pypi](https://pypi.org/project/kprot/) respectively.
83
+
84
+ ## How to use
85
+
86
+ Fill me in please! Don’t forget code examples:
87
+
88
+ ``` python
89
+ 1+1
90
+ ```
91
+
92
+ 2
kprot-0.0.1/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # kprot
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ This file will become your README and also the index of your
7
+ documentation.
8
+
9
+ ## Developer Guide
10
+
11
+ If you are new to using `nbdev` here are some useful pointers to get you
12
+ started.
13
+
14
+ ### Install kprot in Development mode
15
+
16
+ ``` sh
17
+ # make sure kprot package is installed in development mode
18
+ $ pip install -e .
19
+
20
+ # make changes under nbs/ directory
21
+ # ...
22
+
23
+ # compile to have changes apply to kprot
24
+ $ nbdev_prepare
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Installation
30
+
31
+ Install latest from the GitHub
32
+ [repository](https://github.com/sky1ove/kprot):
33
+
34
+ ``` sh
35
+ $ pip install git+https://github.com/sky1ove/kprot.git
36
+ ```
37
+
38
+ or from [conda](https://anaconda.org/sky1ove/kprot)
39
+
40
+ ``` sh
41
+ $ conda install -c sky1ove kprot
42
+ ```
43
+
44
+ or from [pypi](https://pypi.org/project/kprot/)
45
+
46
+ ``` sh
47
+ $ pip install kprot
48
+ ```
49
+
50
+ ### Documentation
51
+
52
+ Documentation can be found hosted on this GitHub
53
+ [repository](https://github.com/sky1ove/kprot)’s
54
+ [pages](https://sky1ove.github.io/kprot/). Additionally you can find
55
+ package manager specific guidelines on
56
+ [conda](https://anaconda.org/sky1ove/kprot) and
57
+ [pypi](https://pypi.org/project/kprot/) respectively.
58
+
59
+ ## How to use
60
+
61
+ Fill me in please! Don’t forget code examples:
62
+
63
+ ``` python
64
+ 1+1
65
+ ```
66
+
67
+ 2
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,22 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/kprot',
5
+ 'doc_host': 'https://sky1ove.github.io',
6
+ 'git_url': 'https://github.com/sky1ove/kprot',
7
+ 'lib_path': 'kprot'},
8
+ 'syms': { 'kprot.embeddings': { 'kprot.embeddings.get_esm': ('embeddings.html#get_esm', 'kprot/embeddings.py'),
9
+ 'kprot.embeddings.get_t5': ('embeddings.html#get_t5', 'kprot/embeddings.py'),
10
+ 'kprot.embeddings.get_t5_bfd': ('embeddings.html#get_t5_bfd', 'kprot/embeddings.py')},
11
+ 'kprot.onehot': { 'kprot.onehot.filter_range_columns': ('onehot_kmeans.html#filter_range_columns', 'kprot/onehot.py'),
12
+ 'kprot.onehot.get_clusters_elbow': ('onehot_kmeans.html#get_clusters_elbow', 'kprot/onehot.py'),
13
+ 'kprot.onehot.onehot_encode': ('onehot_kmeans.html#onehot_encode', 'kprot/onehot.py'),
14
+ 'kprot.onehot.onehot_encode_df': ('onehot_kmeans.html#onehot_encode_df', 'kprot/onehot.py'),
15
+ 'kprot.onehot.run_kmeans': ('onehot_kmeans.html#run_kmeans', 'kprot/onehot.py')},
16
+ 'kprot.uniprot': { 'kprot.uniprot.apply_mut_complex': ('utils.html#apply_mut_complex', 'kprot/uniprot.py'),
17
+ 'kprot.uniprot.apply_mut_single': ('utils.html#apply_mut_single', 'kprot/uniprot.py'),
18
+ 'kprot.uniprot.compare_seq': ('utils.html#compare_seq', 'kprot/uniprot.py'),
19
+ 'kprot.uniprot.get_uniprot_features': ('utils.html#get_uniprot_features', 'kprot/uniprot.py'),
20
+ 'kprot.uniprot.get_uniprot_kd': ('utils.html#get_uniprot_kd', 'kprot/uniprot.py'),
21
+ 'kprot.uniprot.get_uniprot_seq': ('utils.html#get_uniprot_seq', 'kprot/uniprot.py'),
22
+ 'kprot.uniprot.get_uniprot_type': ('utils.html#get_uniprot_type', 'kprot/uniprot.py')}}}
@@ -0,0 +1,165 @@
1
+ """.."""
2
+
3
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_embeddings.ipynb.
4
+
5
+ # %% auto #0
6
+ __all__ = ['def_device', 'get_esm', 'get_t5', 'get_t5_bfd']
7
+
8
+ # %% ../nbs/03_embeddings.ipynb #5ff79e13
9
+ import gc
10
+ import re
11
+
12
+ import pandas as pd
13
+ import torch
14
+ from tqdm.notebook import tqdm; tqdm.pandas()
15
+
16
+ # %% ../nbs/03_embeddings.ipynb #cc83e8ac
17
+ def_device = 'mps' if torch.backends.mps.is_available() else 'cuda' if torch.cuda.is_available() else 'cpu'
18
+
19
+ # %% ../nbs/03_embeddings.ipynb #8400a96d
20
+ def get_esm(
21
+ df: pd.DataFrame, # DataFrame containing protein sequences
22
+ col: str, # column with amino acid sequences
23
+ model_name: str = "esm2_t33_650M_UR50D",
24
+ batch_size: int = 1, # Number of sequences per batch
25
+ ):
26
+ "Extract ESM2 embeddings (mean pooled per sequence)."
27
+
28
+ # model, alphabet = esm.pretrained.load_model_and_alphabet(model_name)
29
+ model, alphabet = torch.hub.load("facebookresearch/esm:main", model_name)
30
+ model = model.to(def_device)
31
+ model.eval()
32
+
33
+ batch_converter = alphabet.get_batch_converter()
34
+
35
+ # Infer repr layer
36
+ match = re.search(r"_t(\d+)_", model_name)
37
+ if not match:
38
+ raise ValueError(f"Cannot infer repr layer from {model_name}")
39
+ layer = int(match.group(1))
40
+
41
+ print(f"Using ESM layer {layer}")
42
+ print("Available models:\n"
43
+ "esm2_t48_15B_UR50D\n"
44
+ "esm2_t36_3B_UR50D\n"
45
+ "esm2_t33_650M_UR50D\n"
46
+ "esm2_t30_150M_UR50D\n"
47
+ "esm2_t12_35M_UR50D\n"
48
+ "esm2_t6_8M_UR50D\n")
49
+
50
+ sequences = df[col].tolist()
51
+ all_embeddings = []
52
+
53
+ for i in tqdm(range(0, len(sequences), batch_size)):
54
+ batch_seqs = sequences[i : i + batch_size]
55
+ data = [(f"seq_{j}", s) for j, s in enumerate(batch_seqs)]
56
+
57
+ batch_labels, batch_strs, batch_tokens = batch_converter(data)
58
+ batch_tokens = batch_tokens.to(def_device)
59
+
60
+ with torch.no_grad():
61
+ results = model(batch_tokens, repr_layers=[layer], return_contacts=False)
62
+
63
+ token_reps = results["representations"][layer]
64
+ batch_lens = (batch_tokens != alphabet.padding_idx).sum(1)
65
+
66
+ for j, seq_len in enumerate(batch_lens):
67
+ # skip BOS (0), stop before EOS
68
+ emb = token_reps[j, 1 : seq_len - 1].mean(0)
69
+ all_embeddings.append(emb.cpu().numpy())
70
+
71
+ del results, token_reps, batch_tokens
72
+ torch.cuda.empty_cache()
73
+ gc.collect()
74
+
75
+ df_emb = pd.DataFrame(
76
+ all_embeddings,
77
+ index=df.index,
78
+ columns=[f"esm_{i}" for i in range(len(all_embeddings[0]))],
79
+ )
80
+
81
+ return df_emb
82
+
83
+ # %% ../nbs/03_embeddings.ipynb #8f95abe4
84
+ def get_t5(df: pd.DataFrame,
85
+ col: str = 'sequence'
86
+ ):
87
+ "Extract ProtT5-XL-uniref50 embeddings from protein sequence in a dataframe"
88
+ from transformers import T5Tokenizer, T5EncoderModel
89
+
90
+ # Reference: https://github.com/agemagician/ProtTrans/tree/master/Embedding/PyTorch/Advanced
91
+ # Load the tokenizer
92
+ tokenizer = T5Tokenizer.from_pretrained('Rostlab/prot_t5_xl_half_uniref50-enc', do_lower_case=False)
93
+
94
+ # Load the model
95
+ model = T5EncoderModel.from_pretrained("Rostlab/prot_t5_xl_half_uniref50-enc").to(def_device)
96
+
97
+ # Set the model precision based on the device
98
+ model.half()
99
+
100
+ def T5_embeddings(sequence):
101
+ seq_len = len(sequence)
102
+ # Prepare the protein sequences as a list
103
+ sequence = [" ".join(list(re.sub(r"[UZOB]", "X", sequence)))]
104
+
105
+ # Tokenize sequences and pad up to the longest sequence in the batch
106
+ ids = tokenizer.batch_encode_plus(sequence, add_special_tokens=True, padding="longest")
107
+ input_ids = torch.tensor(ids['input_ids']).to(def_device)
108
+ attention_mask = torch.tensor(ids['attention_mask']).to(def_device)
109
+ # Generate embeddings
110
+ with torch.no_grad():
111
+ embedding_rpr = model(input_ids=input_ids, attention_mask=attention_mask)
112
+
113
+ emb_mean = embedding_rpr.last_hidden_state[0][:seq_len].detach().to(torch.float32).cpu().numpy().mean(axis=0)
114
+
115
+ return emb_mean
116
+
117
+ series = df[col].progress_apply(T5_embeddings)
118
+
119
+
120
+ T5_feature = pd.DataFrame(series.tolist(),index=df.index)
121
+ T5_feature.columns = 'T5_' + T5_feature.columns.astype(str)
122
+
123
+ return T5_feature
124
+
125
+ # %% ../nbs/03_embeddings.ipynb #90fd2058
126
+ def get_t5_bfd(df:pd.DataFrame,
127
+ col: str = 'sequence'
128
+ ):
129
+
130
+ "Extract ProtT5-XL-BFD embeddings from protein sequence in a dataframe"
131
+ # Reference: https://github.com/agemagician/ProtTrans/tree/master/Embedding/PyTorch/Advanced
132
+ from transformers import T5Tokenizer, T5Model
133
+ # Load the tokenizer
134
+ tokenizer = T5Tokenizer.from_pretrained('Rostlab/prot_t5_xl_bfd', do_lower_case=False)
135
+
136
+ model = T5Model.from_pretrained("Rostlab/prot_t5_xl_bfd").to(def_device)
137
+
138
+ model.eval()
139
+
140
+ def T5_embeddings_bfd(sequence, device = def_device):
141
+ seq_len = len(sequence)
142
+
143
+ # Prepare the protein sequences as a list
144
+ sequence = [" ".join(list(re.sub(r"[UZOB]", "X", sequence)))]
145
+
146
+ # Tokenize sequences and pad up to the longest sequence in the batch
147
+ ids = tokenizer.batch_encode_plus(sequence, add_special_tokens=True, padding="longest")
148
+ input_ids = torch.tensor(ids['input_ids']).to(def_device)
149
+ attention_mask = torch.tensor(ids['attention_mask']).to(def_device)
150
+
151
+ # Generate embeddings
152
+ with torch.no_grad():
153
+ embedding_rpr = model(input_ids=input_ids, attention_mask=attention_mask, decoder_input_ids = input_ids)
154
+
155
+ emb_mean = embedding_rpr.last_hidden_state[0][:seq_len].detach().to(torch.float32).cpu().numpy().mean(axis=0)
156
+
157
+ return emb_mean
158
+
159
+ series = df[col].progress_apply(T5_embeddings_bfd)
160
+
161
+
162
+ T5_feature = pd.DataFrame(series.tolist(),index=df.index)
163
+ T5_feature.columns = 'T5bfd_' + T5_feature.columns.astype(str)
164
+
165
+ return T5_feature
@@ -0,0 +1,56 @@
1
+ """onehot & kmeans"""
2
+
3
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_onehot_kmeans.ipynb.
4
+
5
+ # %% auto #0
6
+ __all__ = ['onehot_encode', 'onehot_encode_df', 'run_kmeans', 'filter_range_columns', 'get_clusters_elbow']
7
+
8
+ # %% ../nbs/02_onehot_kmeans.ipynb #5ff79e13
9
+ import pandas as pd
10
+ from sklearn.cluster import KMeans
11
+ from sklearn.preprocessing import OneHotEncoder
12
+ from matplotlib import pyplot as plt
13
+
14
+ # %% ../nbs/02_onehot_kmeans.ipynb #0589ced9
15
+ def onehot_encode(sequences, transform_colname=True, n=20):
16
+ encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)
17
+ encoded_array = encoder.fit_transform([list(seq) for seq in sequences])
18
+ colnames = [x[1:] for x in encoder.get_feature_names_out()]
19
+ if transform_colname:
20
+ colnames = [f"{int(item.split('_', 1)[0]) - n}{item.split('_', 1)[1]}" for item in colnames]
21
+ encoded_df = pd.DataFrame(encoded_array)
22
+ encoded_df.columns=colnames
23
+ return encoded_df
24
+
25
+ # %% ../nbs/02_onehot_kmeans.ipynb #56e3bace
26
+ def onehot_encode_df(df,seq_col='site_seq', **kwargs):
27
+ return onehot_encode(df[seq_col],**kwargs)
28
+
29
+ # %% ../nbs/02_onehot_kmeans.ipynb #ca2244e2
30
+ def run_kmeans(onehot,n=2,seed=42):
31
+ "Take onehot encoded and regurn the cluster number."
32
+ kmeans = KMeans(n_clusters=n, random_state=seed,n_init='auto')
33
+ return kmeans.fit_predict(onehot)
34
+
35
+ # %% ../nbs/02_onehot_kmeans.ipynb #9dc8cea5
36
+ def filter_range_columns(df, # df need to have column names of position + aa
37
+ low=-10,high=10):
38
+ positions = df.columns.str[:-1].astype(int)
39
+ mask = (positions >= low) & (positions <= high)
40
+ return df.loc[:,mask]
41
+
42
+ # %% ../nbs/02_onehot_kmeans.ipynb #5f3cf9f9
43
+ def get_clusters_elbow(encoded_data,max_cluster=400, interval=50):
44
+
45
+ wcss = []
46
+ for i in range(1, max_cluster,interval):
47
+ kmeans = KMeans(n_clusters=i, random_state=42)
48
+ kmeans.fit(encoded_data)
49
+ wcss.append(kmeans.inertia_)
50
+
51
+ # Plot the Elbow graph
52
+ plt.figure(figsize=(5, 3))
53
+ plt.plot(range(1, max_cluster,interval), wcss)
54
+ plt.title(f'Elbow Method (n={len(encoded_data)})')
55
+ plt.xlabel('# Clusters')
56
+ plt.ylabel('WCSS')
@@ -0,0 +1,281 @@
1
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_utils.ipynb.
2
+
3
+ # %% auto #0
4
+ __all__ = ['get_uniprot_seq', 'get_uniprot_features', 'get_uniprot_kd', 'get_uniprot_type', 'apply_mut_single',
5
+ 'apply_mut_complex', 'compare_seq']
6
+
7
+ # %% ../nbs/01_utils.ipynb #d1ba401f-ec26-4182-986a-e40837f9a915
8
+ import requests, re
9
+ from functools import lru_cache
10
+
11
+ from Bio.Align import PairwiseAligner
12
+
13
+ # %% ../nbs/01_utils.ipynb #81c804f5-a4d8-4b99-a47e-3355779a1bbd
14
+ @lru_cache()
15
+ def get_uniprot_seq(uniprot_id):
16
+ "Queries the UniProt database to retrieve the protein sequence for a given UniProt ID."
17
+
18
+ url = f"https://www.uniprot.org/uniprot/{uniprot_id}.fasta"
19
+ response = requests.get(url)
20
+
21
+ # Check if the request was successful (status code 200)
22
+ if response.status_code == 200:
23
+ data = response.text
24
+ # The sequence starts after the first line, which is a description
25
+ sequence = ''.join(data.split('\n')[1:]).strip()
26
+ return sequence
27
+ else:
28
+ return f"Error: Unable to retrieve sequence for UniProt ID {uniprot_id}. Status code: {response.status_code}"
29
+
30
+ # %% ../nbs/01_utils.ipynb #68c733a5-bbc9-4373-b9d2-23c545e74316
31
+ @lru_cache()
32
+ def get_uniprot_features(uniprot_id):
33
+ "Given uniprot_id, get specific region for uniprot features."
34
+ # uniprot REST API
35
+ url = f"https://rest.uniprot.org/uniprotkb/{uniprot_id}.json"
36
+ response = requests.get(url)
37
+
38
+ if response.status_code == 200:
39
+ data = response.json()
40
+ # Extract the "features" section which contains information
41
+ features = data.get('features', [])
42
+
43
+ protein_name = (
44
+ data.get("proteinDescription", {})
45
+ .get("recommendedName", {})
46
+ .get("fullName", {})
47
+ .get("value")
48
+ )
49
+
50
+ gene_name = (
51
+ data.get("genes", [{}])[0]
52
+ .get("geneName", {})
53
+ .get("value")
54
+ )
55
+ return {
56
+ "uniprot_id": uniprot_id,
57
+ "protein_name": protein_name,
58
+ "gene_name": gene_name,
59
+ "features": features
60
+ }
61
+ else:
62
+ raise ValueError(f"Failed to retrieve UniProt features for {uniprot_id}")
63
+
64
+ # %% ../nbs/01_utils.ipynb #26d793bb-3f87-4e84-bcf6-6ca62a794b32
65
+ def get_uniprot_kd(uniprot_id):
66
+ "Query 'Domain: Protein kinase' based on UniProt ID and get its sequence info."
67
+ data = get_uniprot_features(uniprot_id)
68
+ seq = get_uniprot_seq(uniprot_id)
69
+ out = []
70
+
71
+ for feature in data['features']:
72
+ if feature.get("type") == "Domain" and "Protein kinase" in feature.get("description", ""):
73
+ start = feature['location']['start']['value']
74
+ end = feature['location']['end']['value']
75
+ out.append({
76
+ "uniprot_id": uniprot_id,
77
+ "protein_name": data["protein_name"],
78
+ "gene_name": data["gene_name"],
79
+ "start": start,
80
+ "end": end,
81
+ "description": feature.get("description", ""),
82
+ "sequence": seq[start-1:end]
83
+ })
84
+
85
+ return out
86
+
87
+ # %% ../nbs/01_utils.ipynb #4005a8aa-f8a1-4b99-819e-d7c08d487bf2
88
+ def get_uniprot_type(uniprot_id,type_='Signal'):
89
+ "Get region sequences based on UniProt ID features."
90
+ data = get_uniprot_features(uniprot_id)
91
+ seq = get_uniprot_seq(uniprot_id)
92
+
93
+ out = []
94
+
95
+ for feature in data['features']:
96
+ if feature.get("type") == type_:
97
+ start = feature['location']['start']['value']
98
+ end = feature['location']['end']['value']
99
+ region = {
100
+ 'uniprot_id': uniprot_id,
101
+ 'type': feature['type'],
102
+ "protein_name": data["protein_name"],
103
+ "gene_name": data["gene_name"],
104
+ 'start': start,
105
+ 'end': end,
106
+ 'description': feature['description'],
107
+ 'sequence': seq[start-1:end]
108
+ }
109
+ out.append(region)
110
+
111
+ if not out:
112
+ available = sorted({f.get("type") for f in data['features'] if f.get("type")})
113
+ print(f"No feature of type '{type_}' found for {uniprot_id}.")
114
+ print(f"Available feature types: {', '.join(available)}")
115
+ return available
116
+
117
+ return out
118
+
119
+ # %% ../nbs/01_utils.ipynb #f06c0c1d-829d-4f9e-bcc2-9457050faaf4
120
+ def apply_mut_single(seq, # protein sequence
121
+ *mutations, # e.g., E709A
122
+ start_pos=1, # if the protein sequence does not start from index 1, indicate the start index to match the mutations
123
+ ):
124
+ "Apply mutations to a protein sequence."
125
+ seq_list = list(seq) # convert to list for mutability
126
+
127
+ for mut in mutations:
128
+ # check mutation format
129
+ if len(mut) < 3: raise ValueError(f"Invalid mutation format: {mut}")
130
+
131
+ from_aa,pos,to_aa = mut[0],int(mut[1:-1])-start_pos,mut[-1]
132
+
133
+ # make sure position is within the sequence length
134
+ if pos < 0 or pos >= len(seq_list): raise IndexError(f"Position {pos + 1} out of range for sequence length {len(seq_list)}")
135
+ # make sure aa from mutations matches the residue on the sequence
136
+ if seq_list[pos] != from_aa: raise ValueError(f"Expected {from_aa} at position {pos + 1}, found {seq_list[pos]}")
137
+
138
+ seq_list[pos] = to_aa
139
+ print('Converted:', mut)
140
+
141
+ return ''.join(seq_list)
142
+
143
+ # %% ../nbs/01_utils.ipynb #5c66ef12-8348-4dc6-affc-04858c1411f5
144
+ def apply_mut_complex(seq, # protein sequence
145
+ mut, # mutation (e.g., G776delinsVC/S783C, G778dupGSP)
146
+ start_pos=1, # if truncated protein sequence, indicate where it starts to match the position of mutation
147
+ ):
148
+ """
149
+ Apply a composite mutation like 'G776delinsVC/S783C' to `seq`,
150
+ assuming `seq[0]` corresponds to residue number `start_pos`.
151
+
152
+ * At most one delins **or** dup is allowed.
153
+ * Point substitutions are executed first; the indel/dup is done last.
154
+ """
155
+ _sub_pat = re.compile(r'^([A-Z])(\d+)([A-Z])$') # e.g. S783C
156
+ _delins_pat = re.compile(r'^([A-Z])(\d+)delins([A-Z]+)$') # e.g. G776delinsVC
157
+ _dup_pat = re.compile(r'^([A-Z])(\d+)dup([A-Z]+)$') # e.g. G778dupGSP
158
+
159
+ seq = list(seq)
160
+ tokens = mut.split('/')
161
+
162
+ # ---------- 1) substitutions (length-neutral) ----------
163
+ for m in tokens:
164
+ if _sub_pat.match(m):
165
+ orig, pos, new = _sub_pat.match(m).groups()
166
+ idx = int(pos) - start_pos
167
+ if seq[idx] != orig:
168
+ raise ValueError(
169
+ f"Mismatch at position {pos}: expected {orig}, got {seq[idx]}"
170
+ )
171
+ seq[idx] = new
172
+
173
+ # ---------- 2) the single length-changing event ----------
174
+ for m in tokens:
175
+ if _delins_pat.match(m):
176
+ orig, pos, ins = _delins_pat.match(m).groups()
177
+ idx = int(pos) - start_pos
178
+ if seq[idx] != orig:
179
+ raise ValueError(
180
+ f"Mismatch at position {pos}: expected {orig}, got {seq[idx]}"
181
+ )
182
+ seq[idx : idx + 1] = list(ins) # replace 1 residue with many
183
+ break
184
+
185
+ if _dup_pat.match(m):
186
+ orig, pos, dup = _dup_pat.match(m).groups()
187
+ idx = int(pos) - start_pos
188
+ if seq[idx] != orig:
189
+ raise ValueError(
190
+ f"Mismatch at position {pos}: expected {orig}, got {seq[idx]}"
191
+ )
192
+ seq[idx + 1 : idx + 1] = list(dup) # insert right after the residue
193
+ break
194
+
195
+ return ''.join(seq)
196
+
197
+ # %% ../nbs/01_utils.ipynb #5ac69a8c-fe83-48fc-926f-b99a15624ce3
198
+ def compare_seq(
199
+ seq1: str,
200
+ seq2: str,
201
+ *,
202
+ start_pos: int = 1,
203
+ label1: str = "Original",
204
+ label2: str = "Mutant",
205
+ visualize: bool = True,
206
+ return_text: bool = False,
207
+ ):
208
+ """
209
+ Align two protein sequences and summarise differences.
210
+ Returns a formatted text block (and can optionally print it).
211
+ """
212
+
213
+ # ----- global alignment using PairwiseAligner -----
214
+ aligner = PairwiseAligner()
215
+ aligner.mode = "global"
216
+ aligner.match_score = 2
217
+ aligner.mismatch_score = -1
218
+ aligner.open_gap_score = -5
219
+ aligner.extend_gap_score = -0.5
220
+
221
+ alignment = aligner.align(seq1, seq2)[0]
222
+ aln1 = alignment.aligned[0]
223
+ aln2 = alignment.aligned[1]
224
+
225
+ # Reconstruct aligned strings from aligned segments
226
+ aligned_seq1, aligned_seq2 = [], []
227
+ i1, i2 = 0, 0
228
+
229
+ for (start1, end1), (start2, end2) in zip(aln1, aln2):
230
+ while i1 < start1:
231
+ aligned_seq1.append(seq1[i1]); aligned_seq2.append('-'); i1 += 1
232
+ while i2 < start2:
233
+ aligned_seq1.append('-'); aligned_seq2.append(seq2[i2]); i2 += 1
234
+ for _ in range(end1 - start1):
235
+ aligned_seq1.append(seq1[i1]); aligned_seq2.append(seq2[i2]); i1 += 1; i2 += 1
236
+
237
+ while i1 < len(seq1):
238
+ aligned_seq1.append(seq1[i1]); aligned_seq2.append('-'); i1 += 1
239
+ while i2 < len(seq2):
240
+ aligned_seq1.append('-'); aligned_seq2.append(seq2[i2]); i2 += 1
241
+
242
+ aln1_str = ''.join(aligned_seq1)
243
+ aln2_str = ''.join(aligned_seq2)
244
+
245
+ # ----- find differences -----
246
+ diffs, raw_i1, raw_i2 = [], 0, 0
247
+ for a1, a2 in zip(aln1_str, aln2_str):
248
+ if a1 != '-' and a2 != '-':
249
+ if a1 != a2:
250
+ diffs.append((start_pos + raw_i1, a1, a2, 'substitution'))
251
+ raw_i1 += 1
252
+ raw_i2 += 1
253
+ elif a1 == '-' and a2 != '-':
254
+ diffs.append((start_pos + raw_i1, '-', a2, 'insertion'))
255
+ raw_i2 += 1
256
+ elif a1 != '-' and a2 == '-':
257
+ diffs.append((start_pos + raw_i1, a1, '-', 'deletion'))
258
+ raw_i1 += 1
259
+
260
+ # ----- build output text -----
261
+ lines = []
262
+ if visualize:
263
+ for block in range(0, len(aln1_str), 80):
264
+ s1_block = aln1_str[block:block + 80]
265
+ s2_block = aln2_str[block:block + 80]
266
+ marker = ''.join(' ' if x == y else '^' for x, y in zip(s1_block, s2_block))
267
+ left_idx = start_pos + len(aln1_str[:block].replace('-', ''))
268
+ right_idx = left_idx + len(s1_block.replace('-', '')) - 1
269
+ lines.append(f"{label1:<10} {left_idx:>5}-{right_idx:<5}: {s1_block}")
270
+ lines.append(f"{label2:<10} {'':>11}: {s2_block}")
271
+ lines.append(f"{'':>22} {marker}\n")
272
+
273
+ lines.append("Differences:")
274
+ for pos, ref, new, kind in diffs:
275
+ lines.append(f" {kind:<12} at {pos:>4}: {ref} → {new}")
276
+
277
+ text = "\n".join(lines)
278
+
279
+ if not return_text: print(text)
280
+
281
+ return text if return_text else None
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: kprot
3
+ Version: 0.0.1
4
+ Summary: nbdev project for kprot
5
+ Author-email: sky1ove <lcai888666@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/sky1ove/kprot
8
+ Project-URL: Documentation, https://sky1ove.github.io/kprot/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: biopython>=1.87
16
+ Requires-Dist: matplotlib>=3.10.8
17
+ Requires-Dist: pandas>=2.3.3
18
+ Requires-Dist: requests>=2.33.1
19
+ Requires-Dist: scikit-learn>=1.7.2
20
+ Requires-Dist: sentencepiece>=0.2.1
21
+ Requires-Dist: torch>=2.11.0
22
+ Requires-Dist: tqdm>=4.67.3
23
+ Requires-Dist: transformers>=5.5.3
24
+ Dynamic: license-file
25
+
26
+ # kprot
27
+
28
+
29
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
30
+
31
+ This file will become your README and also the index of your
32
+ documentation.
33
+
34
+ ## Developer Guide
35
+
36
+ If you are new to using `nbdev` here are some useful pointers to get you
37
+ started.
38
+
39
+ ### Install kprot in Development mode
40
+
41
+ ``` sh
42
+ # make sure kprot package is installed in development mode
43
+ $ pip install -e .
44
+
45
+ # make changes under nbs/ directory
46
+ # ...
47
+
48
+ # compile to have changes apply to kprot
49
+ $ nbdev_prepare
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Installation
55
+
56
+ Install latest from the GitHub
57
+ [repository](https://github.com/sky1ove/kprot):
58
+
59
+ ``` sh
60
+ $ pip install git+https://github.com/sky1ove/kprot.git
61
+ ```
62
+
63
+ or from [conda](https://anaconda.org/sky1ove/kprot)
64
+
65
+ ``` sh
66
+ $ conda install -c sky1ove kprot
67
+ ```
68
+
69
+ or from [pypi](https://pypi.org/project/kprot/)
70
+
71
+ ``` sh
72
+ $ pip install kprot
73
+ ```
74
+
75
+ ### Documentation
76
+
77
+ Documentation can be found hosted on this GitHub
78
+ [repository](https://github.com/sky1ove/kprot)’s
79
+ [pages](https://sky1ove.github.io/kprot/). Additionally you can find
80
+ package manager specific guidelines on
81
+ [conda](https://anaconda.org/sky1ove/kprot) and
82
+ [pypi](https://pypi.org/project/kprot/) respectively.
83
+
84
+ ## How to use
85
+
86
+ Fill me in please! Don’t forget code examples:
87
+
88
+ ``` python
89
+ 1+1
90
+ ```
91
+
92
+ 2
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ kprot/__init__.py
6
+ kprot/_modidx.py
7
+ kprot/embeddings.py
8
+ kprot/onehot.py
9
+ kprot/uniprot.py
10
+ kprot.egg-info/PKG-INFO
11
+ kprot.egg-info/SOURCES.txt
12
+ kprot.egg-info/dependency_links.txt
13
+ kprot.egg-info/entry_points.txt
14
+ kprot.egg-info/requires.txt
15
+ kprot.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ kprot = kprot._modidx:d
@@ -0,0 +1,9 @@
1
+ biopython>=1.87
2
+ matplotlib>=3.10.8
3
+ pandas>=2.3.3
4
+ requests>=2.33.1
5
+ scikit-learn>=1.7.2
6
+ sentencepiece>=0.2.1
7
+ torch>=2.11.0
8
+ tqdm>=4.67.3
9
+ transformers>=5.5.3
@@ -0,0 +1 @@
1
+ kprot
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kprot"
7
+ dynamic = ["version"]
8
+ description = "nbdev project for kprot"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "sky1ove", email = "lcai888666@gmail.com"}]
13
+ keywords = ['nbdev']
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ ]
18
+ dependencies = [
19
+ "biopython>=1.87",
20
+ "matplotlib>=3.10.8",
21
+ "pandas>=2.3.3",
22
+ "requests>=2.33.1",
23
+ "scikit-learn>=1.7.2",
24
+ "sentencepiece>=0.2.1",
25
+ "torch>=2.11.0",
26
+ "tqdm>=4.67.3",
27
+ "transformers>=5.5.3",
28
+ ]
29
+
30
+ [project.urls]
31
+ Repository = "https://github.com/sky1ove/kprot"
32
+ Documentation = "https://sky1ove.github.io/kprot/"
33
+
34
+ [project.entry-points.nbdev]
35
+ kprot = "kprot._modidx:d"
36
+
37
+ [tool.setuptools.dynamic]
38
+ version = {attr = "kprot.__version__"}
39
+
40
+ [tool.setuptools.packages.find]
41
+ include = ["kprot"]
42
+
43
+ [tool.nbdev]
44
+ title = "kprot"
45
+ lib_path = "kprot"
kprot-0.0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+