-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdata_rules.py
More file actions
355 lines (303 loc) · 11.1 KB
/
Copy pathdata_rules.py
File metadata and controls
355 lines (303 loc) · 11.1 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""Rules that MITE data entries need to pass to qualify for merge to main"""
import logging
import requests
from mite_data_lib.config.config import settings
from mite_data_lib.models.validation import ValidationContext, ValidationIssue
logger = logging.getLogger(__name__)
def status(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Correct status for production"""
e = []
w = []
if data.get("status") != "active":
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message="Status is not set to 'active'.",
)
)
return e, w
def reserved(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Accession not reserved"""
e = []
w = []
for key, val in ctx.reserved.items():
if key == data.get("accession"):
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"Accession '{key}' already reserved by {val.by} on {val.date}.",
)
)
return e, w
def duplicate_genpept(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""GenPept ID not already described by MITE"""
e = []
w = []
if genpept := data["enzyme"]["databaseIds"].get("genpept"):
df = ctx.proteins
match = df.loc[df["genpept"] == genpept]
if not match.empty:
for i, row in match.iterrows():
if i != data["accession"]:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"Genpept accession '{row['genpept']!s}' already specified in {i!s}",
)
)
return e, w
def duplicate_uniprot(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Uniprot ID not already described by MITE"""
e = []
w = []
if uniprot := data["enzyme"]["databaseIds"].get("uniprot"):
df = ctx.proteins
match = df.loc[df["uniprot"] == uniprot]
if not match.empty:
for i, row in match.iterrows():
if i != data["accession"]:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"UniProt accession '{row['uniprot']!s}' already specified in {i!s}",
)
)
return e, w
def uniprot_exists(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Uniprot ID can be found in Uniprot repo"""
e = []
w = []
if uniprot := data["enzyme"]["databaseIds"].get("uniprot"):
if uniprot.startswith("UPI"):
url = f"https://rest.uniprot.org/uniparc/{uniprot}.fasta"
else:
url = f"https://rest.uniprot.org/uniprotkb/{uniprot}.fasta"
r = requests.head(url=url, timeout=settings.timeout, allow_redirects=True)
if r.status_code != 200:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"UniProt accession '{uniprot}' not found on Uniprot server",
)
)
return e, w
def genpept_exists(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Uniprot ID can be found in Uniprot repo"""
e = []
w = []
if genpept := data["enzyme"]["databaseIds"].get("genpept"):
r = requests.head(
url=f"https://www.ncbi.nlm.nih.gov/protein/{genpept}",
timeout=settings.timeout,
allow_redirects=False,
)
if r.status_code != 200:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"NCBI Genpept accession '{genpept}' not found on NCBI server",
)
)
return e, w
def wikidata_exists(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Wikidata ID can be found in Wikidata"""
def _build_query(qid: str) -> str:
return f"""
ASK {{
wd:{qid} ?p ?o
}}
"""
def _fetch_result(query: str) -> str | bool:
response = requests.get(
"https://query.wikidata.org/sparql",
params={"query": query},
headers={
"User-Agent": f"mite_data_bot/0.0 (https://github.com/mite_standard/mite_data; {settings.email})",
"Accept": "application/sparql-results+json",
},
timeout=settings.timeout,
)
response.raise_for_status()
rsps = response.json()
return rsps.get("boolean")
e = []
w = []
if wikidata := data["enzyme"]["databaseIds"].get("wikidata"):
if not _fetch_result(query=_build_query(qid=wikidata)):
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"Wikidata ID '{wikidata}' not found or has no statements",
)
)
return e, w
def mibig_exists(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""MIBiG ID valid (mite protein found in protein list)"""
def _mibig_api_call(mid: str) -> bool:
try:
r = requests.get(
url=f"https://mibig-submission-test.bioinformatics.nl/api/export/entry/{mid}",
timeout=settings.timeout,
)
if r.status_code == "404":
return False
r.raise_for_status()
return True
except Exception as err:
logger.warning(
f"Warning: could not connect to MIBiG Submission portal: {err!s}"
)
return False
e = []
w = []
mibig = data["enzyme"]["databaseIds"].get("mibig")
if not mibig:
return e, w
if mibig.startswith("BGC"):
if mibig not in ctx.mibig_proteins:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"MIBIG ID '{mibig}' does not exist in MIBiG v {settings.mibig_version}",
)
)
elif mibig.startswith("new"):
if _mibig_api_call(mibig):
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"Temporary MIBIG ID '{mibig}' exist but cannot be merged before assignment of permanent MIBiG ID.",
)
)
else:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"Temporary MIBIG ID '{mibig}' does not exist in MIBiG Submission portal.",
)
)
else:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"MIBIG ID '{mibig}' does not follow naming convention (does not start with 'BGC' or 'new').",
)
)
return e, w
def ids_matching(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Uniprot ID and Genpept ID point to identical protein sequence"""
e = []
w = []
uniprot = data["enzyme"]["databaseIds"].get("uniprot")
genpept = data["enzyme"]["databaseIds"].get("genpept")
if uniprot and genpept:
try:
if not ctx.seq_service.seq_match(uniprot=uniprot, genpept=genpept):
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"Uniprot ID '{uniprot}' and GenPept ID '{genpept}' resolve to different protein sequences - investigate!",
)
)
except Exception as err:
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"{err!s}",
)
)
return e, w
def check_mibig_protein(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""MIBiG ID valid (mite protein found in protein list)"""
e = []
w = []
genpept = data["enzyme"]["databaseIds"].get("genpept")
mibig = data["enzyme"]["databaseIds"].get("mibig")
if genpept and mibig:
if not genpept in ctx.mibig_proteins.get(mibig, []):
e.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"GenPept ID '{genpept}' not found in MIBiG v {settings.mibig_version} entry '{mibig}' - investigate!",
)
)
return e, w
def check_rhea(
data: dict, ctx: ValidationContext
) -> tuple[list[ValidationIssue], list[ValidationIssue]]:
"""Check if uniprot ID has associated Rhea IDs (not always correct though)"""
def _fetch(acc: str) -> requests.Response:
return requests.get(
url="https://www.rhea-db.org/rhea?",
params={
"query": acc,
"columns": "rhea-id",
"format": "tsv",
"limit": 10,
},
timeout=settings.timeout,
)
e = []
w = []
if uniprot := data["enzyme"]["databaseIds"].get("uniprot"):
known_rhea = set()
for reaction in data["reactions"]:
if val := reaction.get("databaseIds", {}).get("rhea"):
known_rhea.add(val)
try:
response = _fetch(uniprot)
response.raise_for_status()
except requests.exceptions.ConnectTimeout:
logger.warning(f"Warning: could not connect to Rhea: Timeout")
return e, w
except requests.HTTPError:
logger.warning(f"Warning: connecting to Rhea lead to HttpError")
return e, w
if response.status_code == 200:
retrieved_rhea = {
i.removeprefix("RHEA:") for i in response.text.split()[2:]
}
diff = sorted(retrieved_rhea.difference(known_rhea))
for rhea in diff:
w.append(
ValidationIssue(
severity="error",
location=data["accession"],
message=f"UniProt ID '{uniprot}' associated to Rhea entry '{rhea}' but not mentioned in MITE entry. Should it be added?",
)
)
return e, w