-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmseqs_runner.py
240 lines (190 loc) · 6.39 KB
/
mmseqs_runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import hashlib
import numpy as np
import os
import re
import requests
import tarfile
import time
from absl import logging
from typing import NoReturn
class MMSeqs2Runner:
r"""Runner object
NOTE: This is a slightly modified version of Diego del Alamo (github: delalamo)'s mmseqs2.py
Fetches sequence alignment and templates from MMSeqs2 server
Based on the function run_mmseqs2 from ColabFold (sokrypton/ColabFold)
Version 62d7558c91a9809712b022faf9d91d8b183c328c
Relevant publications
----------
* "Clustering huge protein sequence sets in linear time"
https://doi.org/10.1038/s41467-018-04964-5
* "MMseqs2 enables sensitive protein sequence searching for the analysis
of massive data sets"
https://doi.org/10.1038/nbt.3988
Private variables
----------
self.job: Job ID (five-char string)
self.seq: Sequence to search
self.host_url: URL address to ping for data
self.t_url: URL address to ping for templates from PDB
self.n_templates = Number of templates to fetch (default=20)
self.path: Path to use
self.tarfile: Compressed file archive to download
"""
def __init__(
self,
job: str,
seq: str,
host_url: str = "https://a3m.mmseqs.com",
t_url: str = "https://a3m-templates.mmseqs.com/template",
n_templates: int = 20,
):
r"""Initialize runner object
Parameters
----------
job : Job name
seq : Amino acid sequence
host_url : Website to ping for sequence data
t_url : Website to ping for template info
"""
# Clean up sequence
self.seq = self._cleanseq(seq.upper())
# Come up with unique job ID for MMSeqs
self.job = self._define_jobname(job)
# Save everything else
self.host_url = host_url
self.t_url = t_url
self.n_templates = n_templates
self.path = "mmseqs_result"
if not os.path.isdir(self.path):
os.system(f"mkdir { self.path }")
self.tarfile = f"{ self.path }/out.tar.gz"
def _cleanseq(self, seq) -> str:
r"""Cleans the sequence to remove whitespace and noncanonical letters
Parameters
----------
seq : Amino acid sequence (only all 20 here)
Returns
----------
Cleaned up amin acid sequence
"""
if any([aa in seq for aa in "BJOUXZ"]):
logging.warning("Sequence contains non-canonical amino acids!")
logging.warning("Removing B, J, O, U, X, and Z from sequence")
seq = re.sub(r"[BJOUXZ]", "", seq)
return re.sub(r"[^A-Z]", "", "".join(seq.split()))
def _define_jobname(self, job: str) -> str:
r"""Provides a unique five-digit identifier for the job name
Parameters
----------
job : Job name
Returns
----------
Defined job name
"""
return "_".join(
(
re.sub(r"\W+", "", "".join(job.split())),
hashlib.sha1(self.seq.encode()).hexdigest()[:5],
)
)
def _submit(self) -> dict:
r"""Submit job to MMSeqs2 server
Parameters
----------
None
Returns
----------
None
"""
data = {"q": f">101\n{ self.seq }", "mode": "env"}
res = requests.post(f"{ self.host_url }/ticket/msa", data=data)
try:
out = res.json()
except ValueError:
out = {"status": "UNKNOWN"}
return out
def _status(self, idx: str) -> dict:
r"""Check status of job
Parameters
----------
idx : Index assigned by MMSeqs2 server
Returns
----------
None
"""
res = requests.get(f"{ self.host_url }/ticket/{ idx }")
try:
out = res.json()
except ValueError:
out = {"status": "UNKNOWN"}
return out
def _download(self, idx: str, path: str) -> NoReturn:
r"""Download job outputs
Parameters
----------
idx : Index assigned by MMSeqs2 server
path : Path to download data
Returns
----------
None
"""
res = requests.get(f"{ self.host_url }/result/download/{ idx }")
with open(path, "wb") as out:
out.write(res.content)
def _search_mmseqs2(self) -> NoReturn:
r"""Run the search and download results
Heavily modified from ColabFold
Parameters
----------
None
Returns
----------
None
"""
if os.path.isfile(self.tarfile):
return
out = self._submit()
time.sleep(5 + np.random.randint(0, 5))
while out["status"] in ["UNKNOWN", "RATELIMIT"]:
# resubmit
time.sleep(5 + np.random.randint(0, 5))
out = self._submit()
print("MMSeqs job submitted...")
logging.debug(f"ID: { out[ 'id' ] }")
while out["status"] in ["UNKNOWN", "RUNNING", "PENDING"]:
time.sleep(5 + np.random.randint(0, 5))
out = self._status(out["id"])
if out["status"] == "COMPLETE":
print("Starting to download .a3m file...")
self._download(out["id"], self.tarfile)
elif out["status"] == "ERROR":
raise RuntimeError(
" ".join(
(
"MMseqs2 API is giving errors.",
"Please confirm your input is a valid protein sequence.",
"If error persists, please try again in an hour.",
)
)
)
# Modifications here
def run_job(self, pdb_id):
r"""
Run sequence alignments using MMseqs2
Parameters
----------
use_templates: Whether to use templates
Returns
----------
Tuple with [0] string with alignment, and [1] path to template
:param pdb_id: pdb id
"""
self._search_mmseqs2()
# extract a3m files
if not os.path.isfile(os.path.join(self.path, "uniref.a3m")):
with tarfile.open(self.tarfile) as tar_gz:
tar_gz.extractall(self.path)
for member in tar_gz.getmembers():
if "uniref.a3m" in member.name:
tar_gz.extract(member)
os.rename("uniref.a3m", f"{pdb_id}.a3m")