pori-python 0.1.0__py3-none-any.whl
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.
- pori_python/__init__.py +1 -0
- pori_python/graphkb/__init__.py +2 -0
- pori_python/graphkb/constants.py +220 -0
- pori_python/graphkb/genes.py +540 -0
- pori_python/graphkb/match.py +710 -0
- pori_python/graphkb/py.typed +0 -0
- pori_python/graphkb/statement.py +48 -0
- pori_python/graphkb/util.py +523 -0
- pori_python/graphkb/vocab.py +198 -0
- pori_python/ipr/__init__.py +0 -0
- pori_python/ipr/annotate.py +373 -0
- pori_python/ipr/connection.py +214 -0
- pori_python/ipr/constants.py +9 -0
- pori_python/ipr/inputs.py +593 -0
- pori_python/ipr/ipr.py +390 -0
- pori_python/ipr/main.py +512 -0
- pori_python/ipr/py.typed +0 -0
- pori_python/ipr/summary.py +412 -0
- pori_python/ipr/therapeutic_options.py +83 -0
- pori_python/ipr/util.py +173 -0
- pori_python/types.py +177 -0
- pori_python-0.1.0.dist-info/LICENSE +674 -0
- pori_python-0.1.0.dist-info/METADATA +151 -0
- pori_python-0.1.0.dist-info/RECORD +49 -0
- pori_python-0.1.0.dist-info/WHEEL +5 -0
- pori_python-0.1.0.dist-info/dependency_links.txt +1 -0
- pori_python-0.1.0.dist-info/entry_points.txt +2 -0
- pori_python-0.1.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +0 -0
- tests/test_graphkb/__init__.py +0 -0
- tests/test_graphkb/data.py +78 -0
- tests/test_graphkb/test_genes.py +306 -0
- tests/test_graphkb/test_graphkb.py +32 -0
- tests/test_graphkb/test_match.py +662 -0
- tests/test_graphkb/test_statement.py +100 -0
- tests/test_graphkb/test_util.py +151 -0
- tests/test_graphkb/test_vocab.py +85 -0
- tests/test_ipr/__init__.py +0 -0
- tests/test_ipr/constants.py +3 -0
- tests/test_ipr/test_annotate.py +149 -0
- tests/test_ipr/test_connection.py +97 -0
- tests/test_ipr/test_inputs.py +295 -0
- tests/test_ipr/test_ipr.py +338 -0
- tests/test_ipr/test_main.py +154 -0
- tests/test_ipr/test_probe.py +72 -0
- tests/test_ipr/test_summary.py +157 -0
- tests/test_ipr/test_upload.py +274 -0
- tests/test_ipr/test_util.py +29 -0
- tests/test_ipr/util.py +9 -0
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from typing import List, cast
|
|
2
|
+
|
|
3
|
+
from pori_python.types import CategoryBaseTermMapping, Statement, Variant
|
|
4
|
+
|
|
5
|
+
from . import GraphKBConnection
|
|
6
|
+
from .constants import FAILED_REVIEW_STATUS, RELEVANCE_BASE_TERMS, STATEMENT_RETURN_PROPERTIES
|
|
7
|
+
from .util import convert_to_rid_list
|
|
8
|
+
from .vocab import get_terms_set
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def categorize_relevance(
|
|
12
|
+
graphkb_conn: GraphKBConnection,
|
|
13
|
+
relevance_rid: str,
|
|
14
|
+
category_base_terms: CategoryBaseTermMapping = RELEVANCE_BASE_TERMS,
|
|
15
|
+
) -> str:
|
|
16
|
+
"""
|
|
17
|
+
Given the record ID of some relevance term, return the higher level categorization
|
|
18
|
+
"""
|
|
19
|
+
for category, base_terms in category_base_terms:
|
|
20
|
+
term_set = get_terms_set(graphkb_conn, base_terms)
|
|
21
|
+
if relevance_rid in term_set:
|
|
22
|
+
return category
|
|
23
|
+
return ""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_statements_from_variants(
|
|
27
|
+
graphkb_conn: GraphKBConnection, variants: List[Variant], failed_review: bool = False
|
|
28
|
+
) -> List[Statement]:
|
|
29
|
+
"""Given a list of variant records from GraphKB, return related statements.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
graphkb_conn (GraphKBConnection): the graphkb api connection object
|
|
33
|
+
variants (list.<dict>): list of variant records. (Have @rid property.)
|
|
34
|
+
failed_review (bool): Include statements that failed review
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
list.<dict>: list of Statement records from graphkb
|
|
38
|
+
"""
|
|
39
|
+
statements = graphkb_conn.query(
|
|
40
|
+
{
|
|
41
|
+
"target": "Statement",
|
|
42
|
+
"filters": {"conditions": convert_to_rid_list(variants), "operator": "CONTAINSANY"},
|
|
43
|
+
"returnProperties": STATEMENT_RETURN_PROPERTIES,
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
if not failed_review:
|
|
47
|
+
statements = [s for s in statements if s.get("reviewStatus") != FAILED_REVIEW_STATUS]
|
|
48
|
+
return [cast(Statement, s) for s in statements]
|
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
from requests.adapters import HTTPAdapter
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from typing import Any, Dict, Iterable, List, Optional, Union, cast
|
|
12
|
+
from urllib3.util.retry import Retry
|
|
13
|
+
|
|
14
|
+
from pori_python.types import ParsedVariant, PositionalVariant, Record
|
|
15
|
+
|
|
16
|
+
from .constants import DEFAULT_LIMIT, DEFAULT_URL, TYPES_TO_NOTATION, AA_3to1_MAPPING
|
|
17
|
+
|
|
18
|
+
QUERY_CACHE: Dict[Any, Any] = {}
|
|
19
|
+
|
|
20
|
+
# name the logger after the package to make it simple to disable for packages using this one as a dependency
|
|
21
|
+
# https://stackoverflow.com/questions/11029717/how-do-i-disable-log-messages-from-the-requests-library
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("graphkb")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def convert_to_rid_list(records: Iterable[Record]) -> List[str]:
|
|
27
|
+
"""Given a list of records or record id strings, return their record IDs."""
|
|
28
|
+
result = []
|
|
29
|
+
for record in records:
|
|
30
|
+
if isinstance(record, str):
|
|
31
|
+
result.append(record) # assume an @rid string
|
|
32
|
+
else:
|
|
33
|
+
result.append(record["@rid"])
|
|
34
|
+
return result
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class FeatureNotFoundError(Exception):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def looks_like_rid(rid: str) -> bool:
|
|
42
|
+
"""Check if an input string looks like a GraphKB ID."""
|
|
43
|
+
if re.match(r"^#-?\d+:-?\d+$", rid):
|
|
44
|
+
return True
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def convert_aa_3to1(three_letter_notation: str) -> str:
|
|
49
|
+
"""Convert an Input string from 3 letter AA notation to 1 letter AA notation."""
|
|
50
|
+
result = []
|
|
51
|
+
|
|
52
|
+
if ":" in three_letter_notation:
|
|
53
|
+
# do not include the feature/gene in replacements
|
|
54
|
+
pos = three_letter_notation.index(":")
|
|
55
|
+
result.append(three_letter_notation[: pos + 1])
|
|
56
|
+
three_letter_notation = three_letter_notation[pos + 1 :]
|
|
57
|
+
|
|
58
|
+
last_match_end = 0 # exclusive interval [ )
|
|
59
|
+
|
|
60
|
+
for match in re.finditer(r"[A-Z][a-z][a-z]", three_letter_notation):
|
|
61
|
+
# add the in-between string
|
|
62
|
+
result.append(three_letter_notation[last_match_end : match.start()])
|
|
63
|
+
text = three_letter_notation[match.start() : match.end()]
|
|
64
|
+
result.append(AA_3to1_MAPPING.get(text, text))
|
|
65
|
+
last_match_end = match.end()
|
|
66
|
+
|
|
67
|
+
result.append(three_letter_notation[last_match_end:])
|
|
68
|
+
return "".join(result)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def join_url(base_url: str, *parts) -> str:
|
|
72
|
+
"""Join parts of a URL into a full URL."""
|
|
73
|
+
if not parts:
|
|
74
|
+
return base_url
|
|
75
|
+
|
|
76
|
+
url = [base_url.rstrip("/")] + [part.strip("/") for part in parts]
|
|
77
|
+
|
|
78
|
+
return "/".join(url)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def millis_interval(start: datetime, end: datetime) -> int:
|
|
82
|
+
"""Millisecond time from start and end datetime instances."""
|
|
83
|
+
diff = end - start
|
|
84
|
+
millis = diff.days * 24 * 60 * 60 * 1000
|
|
85
|
+
millis += diff.seconds * 1000
|
|
86
|
+
millis += diff.microseconds // 1000
|
|
87
|
+
return millis
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def cache_key(request_body) -> str:
|
|
91
|
+
"""Create a cache key for a query request to GraphKB."""
|
|
92
|
+
body = json.dumps(request_body, sort_keys=True)
|
|
93
|
+
hash_code = hashlib.md5(f"/query{body}".encode("utf-8")).hexdigest()
|
|
94
|
+
return hash_code
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class GraphKBConnection:
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
url: str = os.environ.get("GRAPHKB_URL", DEFAULT_URL),
|
|
101
|
+
username: str = "",
|
|
102
|
+
password: str = "",
|
|
103
|
+
use_global_cache: bool = True,
|
|
104
|
+
):
|
|
105
|
+
self.http = requests.Session()
|
|
106
|
+
retries = Retry(
|
|
107
|
+
total=100,
|
|
108
|
+
connect=5,
|
|
109
|
+
status=5,
|
|
110
|
+
backoff_factor=5,
|
|
111
|
+
status_forcelist=[429, 500, 502, 503, 504],
|
|
112
|
+
)
|
|
113
|
+
self.http.mount("https://", HTTPAdapter(max_retries=retries))
|
|
114
|
+
self.token = ""
|
|
115
|
+
self.url = url
|
|
116
|
+
self.username = username
|
|
117
|
+
self.password = password
|
|
118
|
+
self.headers = {"Accept": "application/json", "Content-Type": "application/json"}
|
|
119
|
+
self.cache: Dict[Any, Any] = {} if not use_global_cache else QUERY_CACHE
|
|
120
|
+
self.request_count = 0
|
|
121
|
+
self.first_request: Optional[datetime] = None
|
|
122
|
+
self.last_request: Optional[datetime] = None
|
|
123
|
+
if username and password:
|
|
124
|
+
self.login(username=username, password=password)
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def load(self) -> Optional[float]:
|
|
128
|
+
if self.first_request and self.last_request:
|
|
129
|
+
return (
|
|
130
|
+
self.request_count * 1000 / millis_interval(self.first_request, self.last_request)
|
|
131
|
+
)
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
def request(self, endpoint: str, method: str = "GET", **kwargs) -> Dict:
|
|
135
|
+
"""Request wrapper to handle adding common headers and logging.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
endpoint (string): api endpoint, excluding the base uri
|
|
139
|
+
method (str, optional): the http method. Defaults to 'GET'.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
dict: the json response as a python dict
|
|
143
|
+
"""
|
|
144
|
+
url = join_url(self.url, endpoint)
|
|
145
|
+
self.request_count += 1
|
|
146
|
+
connect_timeout = 7
|
|
147
|
+
read_timeout = 61
|
|
148
|
+
|
|
149
|
+
# don't want to use a read timeout if the request is not idempotent
|
|
150
|
+
# otherwise you may wind up making unintended changes
|
|
151
|
+
timeout = None
|
|
152
|
+
if endpoint in ["query", "parse"]:
|
|
153
|
+
timeout = (connect_timeout, read_timeout)
|
|
154
|
+
|
|
155
|
+
start_time = datetime.now()
|
|
156
|
+
|
|
157
|
+
if not self.first_request:
|
|
158
|
+
self.first_request = start_time
|
|
159
|
+
self.last_request = start_time
|
|
160
|
+
|
|
161
|
+
# using a manual retry as well as using the requests Retry() object because
|
|
162
|
+
# a ConnectionError or OSError might be thrown and we still want to retry in those cases.
|
|
163
|
+
# about catching OSError as well as ConnectionError:
|
|
164
|
+
# https://stackoverflow.com/questions/74253820
|
|
165
|
+
attempts = range(15)
|
|
166
|
+
for attempt in attempts:
|
|
167
|
+
if attempt > 0:
|
|
168
|
+
time.sleep(2) # wait between retries
|
|
169
|
+
try:
|
|
170
|
+
self.refresh_login()
|
|
171
|
+
self.request_count += 1
|
|
172
|
+
resp = requests.request(
|
|
173
|
+
method, url, headers=self.headers, timeout=timeout, **kwargs
|
|
174
|
+
)
|
|
175
|
+
if resp.status_code == 401 or resp.status_code == 403:
|
|
176
|
+
logger.debug(f"/{endpoint} - {resp.status_code} - retrying")
|
|
177
|
+
# try to re-login if the token expired
|
|
178
|
+
continue
|
|
179
|
+
else:
|
|
180
|
+
break
|
|
181
|
+
except (requests.exceptions.ConnectionError, OSError) as err:
|
|
182
|
+
if attempt < len(attempts) - 1:
|
|
183
|
+
logger.debug(f"/{endpoint} - {str(err)} - retrying")
|
|
184
|
+
continue
|
|
185
|
+
raise err
|
|
186
|
+
except Exception as err2:
|
|
187
|
+
raise err2
|
|
188
|
+
|
|
189
|
+
timing = millis_interval(start_time, datetime.now())
|
|
190
|
+
logger.debug(f"/{endpoint} - {resp.status_code} - {timing} ms") # type: ignore
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
resp.raise_for_status()
|
|
194
|
+
except requests.exceptions.HTTPError as err:
|
|
195
|
+
# try to get more error details
|
|
196
|
+
message = str(err)
|
|
197
|
+
try:
|
|
198
|
+
message += " " + resp.json()["message"]
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
|
|
202
|
+
raise requests.exceptions.HTTPError(message)
|
|
203
|
+
|
|
204
|
+
return resp.json()
|
|
205
|
+
|
|
206
|
+
def post(self, uri: str, data: Dict = {}, **kwargs) -> Dict:
|
|
207
|
+
"""Convenience method for making post requests."""
|
|
208
|
+
return self.request(uri, method="POST", data=json.dumps(data), **kwargs)
|
|
209
|
+
|
|
210
|
+
def login(self, username: str, password: str) -> None:
|
|
211
|
+
self.username = username
|
|
212
|
+
self.password = password
|
|
213
|
+
connect_timeout = 7
|
|
214
|
+
read_timeout = 61
|
|
215
|
+
|
|
216
|
+
# use requests package directly to avoid recursion loop on login failure
|
|
217
|
+
attempts = range(10)
|
|
218
|
+
for attempt in attempts:
|
|
219
|
+
if attempt > 0:
|
|
220
|
+
time.sleep(2) # wait between retries
|
|
221
|
+
try:
|
|
222
|
+
self.request_count += 1
|
|
223
|
+
resp = requests.request(
|
|
224
|
+
url=f"{self.url}/token",
|
|
225
|
+
method="POST",
|
|
226
|
+
headers=self.headers,
|
|
227
|
+
timeout=(connect_timeout, read_timeout),
|
|
228
|
+
data=json.dumps({"username": username, "password": password}),
|
|
229
|
+
)
|
|
230
|
+
break
|
|
231
|
+
except (requests.exceptions.ConnectionError, OSError) as err:
|
|
232
|
+
if attempt < len(attempts) - 1:
|
|
233
|
+
logger.debug(f"/login - {str(err)} - retrying")
|
|
234
|
+
continue
|
|
235
|
+
raise err
|
|
236
|
+
except Exception as err2:
|
|
237
|
+
raise err2
|
|
238
|
+
resp.raise_for_status()
|
|
239
|
+
content = resp.json()
|
|
240
|
+
self.token = content["kbToken"]
|
|
241
|
+
self.headers["Authorization"] = self.token
|
|
242
|
+
|
|
243
|
+
def refresh_login(self) -> None:
|
|
244
|
+
self.login(self.username, self.password)
|
|
245
|
+
|
|
246
|
+
def set_cache_data(self, request_body: Dict, result: List[Record]) -> None:
|
|
247
|
+
"""Explicitly add a query to the cache."""
|
|
248
|
+
hash_code = cache_key(request_body)
|
|
249
|
+
self.cache[hash_code] = result
|
|
250
|
+
|
|
251
|
+
def query(
|
|
252
|
+
self,
|
|
253
|
+
request_body: Dict = {},
|
|
254
|
+
paginate: bool = True,
|
|
255
|
+
ignore_cache: bool = False,
|
|
256
|
+
force_refresh: bool = False,
|
|
257
|
+
limit: int = DEFAULT_LIMIT,
|
|
258
|
+
) -> List[Record]:
|
|
259
|
+
"""
|
|
260
|
+
Query GraphKB
|
|
261
|
+
"""
|
|
262
|
+
result: List[Record] = []
|
|
263
|
+
hash_code = ""
|
|
264
|
+
|
|
265
|
+
if not ignore_cache and paginate:
|
|
266
|
+
hash_code = cache_key(request_body)
|
|
267
|
+
if hash_code in self.cache and not force_refresh:
|
|
268
|
+
return self.cache[hash_code]
|
|
269
|
+
|
|
270
|
+
while True:
|
|
271
|
+
content = self.post("query", data={**request_body, "limit": limit, "skip": len(result)})
|
|
272
|
+
records = content["result"]
|
|
273
|
+
result.extend(records)
|
|
274
|
+
if len(records) < limit or not paginate:
|
|
275
|
+
break
|
|
276
|
+
|
|
277
|
+
if not ignore_cache and paginate:
|
|
278
|
+
self.cache[hash_code] = result
|
|
279
|
+
return result
|
|
280
|
+
|
|
281
|
+
def parse(self, hgvs_string: str, requireFeatures: bool = False) -> ParsedVariant:
|
|
282
|
+
content = self.post(
|
|
283
|
+
"parse", data={"content": hgvs_string, "requireFeatures": requireFeatures}
|
|
284
|
+
)
|
|
285
|
+
return cast(ParsedVariant, content["result"])
|
|
286
|
+
|
|
287
|
+
def get_records_by_id(self, record_ids: List[str]) -> List[Record]:
|
|
288
|
+
if not record_ids:
|
|
289
|
+
return []
|
|
290
|
+
result = self.query({"target": record_ids})
|
|
291
|
+
if len(record_ids) != len(result):
|
|
292
|
+
raise AssertionError(
|
|
293
|
+
f"The number of Ids given ({len(record_ids)}) does not match the number of records fetched ({len(result)})"
|
|
294
|
+
)
|
|
295
|
+
return result
|
|
296
|
+
|
|
297
|
+
def get_record_by_id(self, record_id: str) -> Record:
|
|
298
|
+
result = self.get_records_by_id([record_id])
|
|
299
|
+
return result[0]
|
|
300
|
+
|
|
301
|
+
def get_source(self, name: str) -> Record:
|
|
302
|
+
source = self.query({"target": "Source", "filters": {"name": name}})
|
|
303
|
+
if len(source) != 1:
|
|
304
|
+
raise AssertionError(f"Unable to unqiuely identify source with name {name}")
|
|
305
|
+
return source[0]
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def get_rid(conn: GraphKBConnection, target: str, name: str) -> str:
|
|
309
|
+
"""
|
|
310
|
+
Retrieve a record by name and target
|
|
311
|
+
|
|
312
|
+
Args:
|
|
313
|
+
conn: GraphKBConnection
|
|
314
|
+
target: record type to query
|
|
315
|
+
name: the name of the record to retrieve
|
|
316
|
+
|
|
317
|
+
Returns:
|
|
318
|
+
str: @rid of the record
|
|
319
|
+
|
|
320
|
+
Raises:
|
|
321
|
+
AssertionError: if the term was not found or more than 1 match was found (expected to be unique)
|
|
322
|
+
"""
|
|
323
|
+
result = conn.query(
|
|
324
|
+
{"target": target, "filters": {"name": name}, "returnProperties": ["@rid"]},
|
|
325
|
+
ignore_cache=False,
|
|
326
|
+
)
|
|
327
|
+
assert len(result) == 1, f"unable to find unique '{target}' ID for '{name}'"
|
|
328
|
+
|
|
329
|
+
return result[0]["@rid"]
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def stripParentheses(breakRepr: str) -> str:
|
|
333
|
+
match = re.search(r"^([a-z])\.\((.+)\)$", breakRepr)
|
|
334
|
+
|
|
335
|
+
if match:
|
|
336
|
+
return f"{match.group(1)}.{match.group(2)}"
|
|
337
|
+
return breakRepr
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def stripRefSeq(breakRepr: str) -> str:
|
|
341
|
+
# 1 leading RefSeq
|
|
342
|
+
match = re.search(r"^([a-z])\.([A-Z]*|\?)([0-9]*[A-Z]*)$", breakRepr)
|
|
343
|
+
if match:
|
|
344
|
+
return f"{match.group(1)}.{match.group(3)}"
|
|
345
|
+
|
|
346
|
+
# TODO: Deal with cases like "p.?889_?890", "chr4:g.55593604_55593605delGGinsTT", ...
|
|
347
|
+
|
|
348
|
+
return breakRepr
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def stripDisplayName(displayName: str, withRef: bool = True, withRefSeq: bool = True) -> str:
|
|
352
|
+
match = re.search(r"^(.*)(\:)(.*)$", displayName)
|
|
353
|
+
if match and not withRef:
|
|
354
|
+
if withRefSeq:
|
|
355
|
+
return match.group(3)
|
|
356
|
+
displayName = match.group(2) + match.group(3)
|
|
357
|
+
|
|
358
|
+
match = re.search(r"^(.*\:)([a-z]\.)(.*)$", displayName)
|
|
359
|
+
if match and not withRefSeq:
|
|
360
|
+
ref: str = match.group(1) if match.group(1) != ":" else ""
|
|
361
|
+
prefix: str = match.group(2)
|
|
362
|
+
rest: str = match.group(3)
|
|
363
|
+
new_matches: Union[bool, object] = True
|
|
364
|
+
|
|
365
|
+
# refSeq before position
|
|
366
|
+
while new_matches:
|
|
367
|
+
new_matches = re.search(r"(.*)([A-Z]|\?)([0-9]+)(.*)", rest)
|
|
368
|
+
if new_matches:
|
|
369
|
+
rest = new_matches.group(1) + new_matches.group(3) + new_matches.group(4)
|
|
370
|
+
|
|
371
|
+
# refSeq before '>'
|
|
372
|
+
new_matches = re.search(r"^([0-9]*)([A-Z]*|\?)(\>)(.*)$", rest)
|
|
373
|
+
if new_matches:
|
|
374
|
+
rest = new_matches.group(1) + new_matches.group(3) + new_matches.group(4)
|
|
375
|
+
|
|
376
|
+
displayName = ref + prefix + rest
|
|
377
|
+
|
|
378
|
+
# TODO: Deal with more complex cases like fusion, cds with offset (ex. 'VHL:c.464-2G>A')
|
|
379
|
+
# and other complex cases (ex. 'VHL:c.330_331delCAinsTT')
|
|
380
|
+
|
|
381
|
+
return displayName
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def stringifyVariant(
|
|
385
|
+
variant: Union[PositionalVariant, ParsedVariant], withRef: bool = True, withRefSeq: bool = True
|
|
386
|
+
) -> str:
|
|
387
|
+
"""
|
|
388
|
+
Convert variant record to a string representation (displayName/hgvs)
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
variant: the input variant
|
|
392
|
+
withRef (bool, optional): include the reference part
|
|
393
|
+
withRefSeq (bool, optional): include the reference sequence in the variant part
|
|
394
|
+
|
|
395
|
+
Returns:
|
|
396
|
+
str: The string representation
|
|
397
|
+
"""
|
|
398
|
+
|
|
399
|
+
displayName: str = variant.get("displayName") or "" # type: ignore
|
|
400
|
+
|
|
401
|
+
# If variant is a PositionalVariant (i.e. variant with a displayName) and
|
|
402
|
+
# we already have the appropriate string representation,
|
|
403
|
+
# then return it right away
|
|
404
|
+
if displayName != "" and (withRef and withRefSeq):
|
|
405
|
+
return displayName
|
|
406
|
+
|
|
407
|
+
# If variant is a PositionalVariant (i.e. variant with a displayName) and
|
|
408
|
+
# we DO NOT have the appropriate string representation,
|
|
409
|
+
# then strip unwanted features, then return it right away
|
|
410
|
+
if displayName != "":
|
|
411
|
+
return stripDisplayName(displayName, withRef, withRefSeq)
|
|
412
|
+
|
|
413
|
+
# If variant is a ParsedVariant (i.e. variant without a displayName yet),
|
|
414
|
+
# the following will return a stringify representation (displayName/hgvs) of that variant
|
|
415
|
+
# based on: https://github.com/bcgsc/pori_graphkb_parser/blob/ae3738842a4c208ab30f58c08ae987594d632504/src/variant.ts#L206-L292
|
|
416
|
+
|
|
417
|
+
parsed = variant
|
|
418
|
+
result: List[str] = []
|
|
419
|
+
|
|
420
|
+
# Extracting parsed values into individual variables
|
|
421
|
+
break1Repr: str = str(parsed.get("break1Repr", ""))
|
|
422
|
+
break2Repr: str = str(parsed.get("break2Repr", ""))
|
|
423
|
+
multiFeature: bool = bool(parsed.get("multiFeature"))
|
|
424
|
+
noFeatures: bool = bool(parsed.get("noFeatures"))
|
|
425
|
+
notationType: str = str(parsed.get("notationType", ""))
|
|
426
|
+
reference1: str = ""
|
|
427
|
+
if ref1 := parsed.get("reference1"):
|
|
428
|
+
if isinstance(ref1, str):
|
|
429
|
+
reference1 = ref1
|
|
430
|
+
else:
|
|
431
|
+
reference1 = ref1.get("displayName", str(ref1))
|
|
432
|
+
reference2: str = ""
|
|
433
|
+
if ref2 := parsed.get("reference2"):
|
|
434
|
+
if isinstance(ref2, str):
|
|
435
|
+
reference2 = ref2
|
|
436
|
+
else:
|
|
437
|
+
reference2 = ref2.get("displayName", str(ref2))
|
|
438
|
+
refSeq: str = parsed.get("refSeq") or ""
|
|
439
|
+
truncation: int = parsed.get("truncation") or 0 # type: ignore
|
|
440
|
+
variantType: str = parsed.get("type", "")
|
|
441
|
+
untemplatedSeq: str = parsed.get("untemplatedSeq") or ""
|
|
442
|
+
untemplatedSeqSize: int = parsed.get("untemplatedSeqSize") or 0
|
|
443
|
+
|
|
444
|
+
# formating notationType
|
|
445
|
+
if not notationType:
|
|
446
|
+
notationType = TYPES_TO_NOTATION.get(variantType, re.sub(r"\s", "-", variantType))
|
|
447
|
+
|
|
448
|
+
# If multiFeature
|
|
449
|
+
if multiFeature or (reference2 != "" and reference1 != reference2):
|
|
450
|
+
if withRef and not noFeatures:
|
|
451
|
+
result.append(f"({reference1}:{reference2})")
|
|
452
|
+
result.append(notationType)
|
|
453
|
+
if withRefSeq:
|
|
454
|
+
break1Repr_noParentheses = stripParentheses(break1Repr)
|
|
455
|
+
break2Repr_noParentheses = stripParentheses(break2Repr)
|
|
456
|
+
result.append(f"({break1Repr_noParentheses},{break2Repr_noParentheses})")
|
|
457
|
+
else:
|
|
458
|
+
break1Repr_noParentheses_noRefSeq = stripRefSeq(stripParentheses(break1Repr))
|
|
459
|
+
break2Repr_noParentheses_noRefSeq = stripRefSeq(stripParentheses(break2Repr))
|
|
460
|
+
result.append(
|
|
461
|
+
f"({break1Repr_noParentheses_noRefSeq},{break2Repr_noParentheses_noRefSeq})"
|
|
462
|
+
)
|
|
463
|
+
if untemplatedSeq != "":
|
|
464
|
+
result.append(untemplatedSeq)
|
|
465
|
+
elif untemplatedSeqSize:
|
|
466
|
+
result.append(str(untemplatedSeqSize))
|
|
467
|
+
return "".join(result)
|
|
468
|
+
|
|
469
|
+
# Continuous notation...
|
|
470
|
+
|
|
471
|
+
# Reference
|
|
472
|
+
if withRef and not noFeatures:
|
|
473
|
+
result.append(f"{reference1}:")
|
|
474
|
+
|
|
475
|
+
# BreakRep
|
|
476
|
+
if withRefSeq:
|
|
477
|
+
result.append(break1Repr)
|
|
478
|
+
if break2Repr != "":
|
|
479
|
+
result.append(f"_{break2Repr[2:]}")
|
|
480
|
+
else:
|
|
481
|
+
result.append(stripRefSeq(break1Repr))
|
|
482
|
+
if break2Repr != "":
|
|
483
|
+
result.append(f"_{stripRefSeq(break2Repr)[2:]}")
|
|
484
|
+
|
|
485
|
+
# refSeq, truncation, notationType, untemplatedSeq, untemplatedSeqSize
|
|
486
|
+
if any(i in notationType for i in ["ext", "fs"]) or (
|
|
487
|
+
notationType == ">" and break1Repr.startswith("p.")
|
|
488
|
+
):
|
|
489
|
+
result.append(untemplatedSeq)
|
|
490
|
+
if notationType == "mis" and break1Repr.startswith("p."):
|
|
491
|
+
result.append(untemplatedSeq)
|
|
492
|
+
elif notationType != ">":
|
|
493
|
+
if notationType == "delins":
|
|
494
|
+
if withRefSeq:
|
|
495
|
+
result.append(f"del{refSeq}ins")
|
|
496
|
+
else:
|
|
497
|
+
result.append("delins")
|
|
498
|
+
else:
|
|
499
|
+
result.append(notationType)
|
|
500
|
+
if truncation and truncation != 1:
|
|
501
|
+
if truncation < 0:
|
|
502
|
+
result.append(str(truncation))
|
|
503
|
+
else:
|
|
504
|
+
result.append(f"*{truncation}")
|
|
505
|
+
if any(i in notationType for i in ["dup", "del", "inv"]):
|
|
506
|
+
if withRefSeq:
|
|
507
|
+
result.append(refSeq)
|
|
508
|
+
if any(i in notationType for i in ["ins", "delins"]):
|
|
509
|
+
if untemplatedSeq != "":
|
|
510
|
+
result.append(untemplatedSeq)
|
|
511
|
+
elif untemplatedSeqSize:
|
|
512
|
+
result.append(str(untemplatedSeqSize))
|
|
513
|
+
elif not break1Repr.startswith("p."):
|
|
514
|
+
if withRefSeq:
|
|
515
|
+
refSeq = refSeq if refSeq != "" else "?"
|
|
516
|
+
else:
|
|
517
|
+
refSeq = ""
|
|
518
|
+
untemplatedSeq = untemplatedSeq if untemplatedSeq != "" else "?"
|
|
519
|
+
result.append(f"{refSeq}{notationType}{untemplatedSeq}")
|
|
520
|
+
|
|
521
|
+
# TODO: Deal with more complexes cases like 'MED12:p.(?34_?68)mut'
|
|
522
|
+
|
|
523
|
+
return "".join(result)
|