pori-python 1.1.0__tar.gz → 1.2.2__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.
Files changed (57) hide show
  1. {pori_python-1.1.0/pori_python.egg-info → pori_python-1.2.2}/PKG-INFO +13 -1
  2. {pori_python-1.1.0 → pori_python-1.2.2}/README.md +12 -0
  3. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/graphkb/match.py +9 -9
  4. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/graphkb/util.py +45 -5
  5. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/annotate.py +3 -3
  6. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/connection.py +35 -3
  7. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/constants.py +8 -8
  8. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/inputs.py +8 -6
  9. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/ipr.py +65 -19
  10. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/main.py +59 -19
  11. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/summary.py +7 -7
  12. {pori_python-1.1.0 → pori_python-1.2.2/pori_python.egg-info}/PKG-INFO +13 -1
  13. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python.egg-info/SOURCES.txt +1 -2
  14. {pori_python-1.1.0 → pori_python-1.2.2}/setup.cfg +3 -3
  15. pori_python-1.2.2/tests/test_graphkb/data.py +198 -0
  16. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_graphkb/test_match.py +13 -1
  17. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_annotate.py +6 -8
  18. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_inputs.py +2 -2
  19. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_ipr.py +56 -30
  20. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_main.py +1 -1
  21. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_probe.py +1 -1
  22. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_summary.py +75 -75
  23. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_upload.py +4 -3
  24. pori_python-1.1.0/pori_python/ipr/py.typed +0 -0
  25. pori_python-1.1.0/tests/test_graphkb/data.py +0 -78
  26. {pori_python-1.1.0 → pori_python-1.2.2}/LICENSE +0 -0
  27. {pori_python-1.1.0 → pori_python-1.2.2}/MANIFEST.in +0 -0
  28. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/__init__.py +0 -0
  29. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/graphkb/__init__.py +0 -0
  30. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/graphkb/constants.py +0 -0
  31. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/graphkb/genes.py +0 -0
  32. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/graphkb/statement.py +0 -0
  33. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/graphkb/vocab.py +0 -0
  34. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/__init__.py +0 -0
  35. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/content.spec.json +0 -0
  36. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/therapeutic_options.py +0 -0
  37. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/ipr/util.py +0 -0
  38. {pori_python-1.1.0/pori_python/graphkb → pori_python-1.2.2/pori_python}/py.typed +0 -0
  39. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python/types.py +0 -0
  40. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python.egg-info/dependency_links.txt +0 -0
  41. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python.egg-info/entry_points.txt +0 -0
  42. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python.egg-info/requires.txt +0 -0
  43. {pori_python-1.1.0 → pori_python-1.2.2}/pori_python.egg-info/top_level.txt +0 -0
  44. {pori_python-1.1.0 → pori_python-1.2.2}/pyproject.toml +0 -0
  45. {pori_python-1.1.0 → pori_python-1.2.2}/setup.py +0 -0
  46. {pori_python-1.1.0 → pori_python-1.2.2}/tests/__init__.py +0 -0
  47. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_graphkb/__init__.py +0 -0
  48. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_graphkb/test_genes.py +0 -0
  49. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_graphkb/test_graphkb.py +0 -0
  50. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_graphkb/test_statement.py +0 -0
  51. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_graphkb/test_util.py +0 -0
  52. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_graphkb/test_vocab.py +0 -0
  53. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/__init__.py +0 -0
  54. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/constants.py +0 -0
  55. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_connection.py +0 -0
  56. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/test_util.py +0 -0
  57. {pori_python-1.1.0 → pori_python-1.2.2}/tests/test_ipr/util.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pori_python
3
- Version: 1.1.0
3
+ Version: 1.2.2
4
4
  Home-page: https://github.com/bcgsc/pori_python
5
5
  Author-email: dat@bcgsc.ca
6
6
  Maintainer-email: dat@bcgsc.ca
@@ -61,6 +61,7 @@ For documentation on how to create reports using the IPR adaptor, see the [main
61
61
 
62
62
  - [Getting Started](#getting-started)
63
63
  - [Install (For developers)](#install-for-developers)
64
+ - [JSON Validate and Upload to IPR](#json-validate-and-upload-to-ipr)
64
65
  - [Documentation](#documentation)
65
66
  - [Deployment (Publishing)](#deployment-publishing)
66
67
 
@@ -128,6 +129,17 @@ export DELETE_UPLOAD_TEST_REPORTS=0
128
129
  pytest tests
129
130
  ```
130
131
 
132
+ ### JSON Validate and Upload to IPR
133
+ If you only want to validate the json content, use
134
+ ```bash
135
+ ipr --password $IPR_PASS -c 'path/to/content.json' --validate_json
136
+ ```
137
+
138
+ If you only want to upload the json directly to ipr and skip all the preprocessing, use
139
+ ```bash
140
+ ipr --password $IPR_PASS -c 'path/to/content.json' --upload_json
141
+ ```
142
+
131
143
  ## Documentation
132
144
 
133
145
  The user documentation for this tool is hosted with the [main documentation site](https://bcgsc.github.io/pori/).
@@ -15,6 +15,7 @@ For documentation on how to create reports using the IPR adaptor, see the [main
15
15
 
16
16
  - [Getting Started](#getting-started)
17
17
  - [Install (For developers)](#install-for-developers)
18
+ - [JSON Validate and Upload to IPR](#json-validate-and-upload-to-ipr)
18
19
  - [Documentation](#documentation)
19
20
  - [Deployment (Publishing)](#deployment-publishing)
20
21
 
@@ -82,6 +83,17 @@ export DELETE_UPLOAD_TEST_REPORTS=0
82
83
  pytest tests
83
84
  ```
84
85
 
86
+ ### JSON Validate and Upload to IPR
87
+ If you only want to validate the json content, use
88
+ ```bash
89
+ ipr --password $IPR_PASS -c 'path/to/content.json' --validate_json
90
+ ```
91
+
92
+ If you only want to upload the json directly to ipr and skip all the preprocessing, use
93
+ ```bash
94
+ ipr --password $IPR_PASS -c 'path/to/content.json' --upload_json
95
+ ```
96
+
85
97
  ## Documentation
86
98
 
87
99
  The user documentation for this tool is hosted with the [main documentation site](https://bcgsc.github.io/pori/).
@@ -135,7 +135,7 @@ def match_category_variant(
135
135
  gene_source: str = "",
136
136
  gene_is_source_id: bool = False,
137
137
  ignore_cache: bool = False,
138
- reference_class: str = 'Feature',
138
+ reference_class: str = "Feature",
139
139
  ) -> List[Variant]:
140
140
  """
141
141
  Returns a list of variants matching the input variant
@@ -155,7 +155,7 @@ def match_category_variant(
155
155
  """
156
156
  # disambiguate the reference to find all equivalent representations
157
157
  references: List[str] = []
158
- if reference_class == 'Feature':
158
+ if reference_class == "Feature":
159
159
  references = convert_to_rid_list(
160
160
  get_equivalent_features(
161
161
  conn,
@@ -169,12 +169,12 @@ def match_category_variant(
169
169
  raise FeatureNotFoundError(
170
170
  f"unable to find the gene ({reference_name}) or any equivalent representations"
171
171
  )
172
- if reference_class == 'Signature':
172
+ if reference_class == "Signature":
173
173
  references = convert_to_rid_list(
174
174
  get_equivalent_terms(
175
175
  conn,
176
176
  reference_name.lower(),
177
- ontology_class='Signature',
177
+ ontology_class="Signature",
178
178
  ignore_cache=ignore_cache,
179
179
  )
180
180
  )
@@ -315,16 +315,16 @@ def equivalent_types(
315
315
 
316
316
  # Convert rid to displayName if needed
317
317
  if looks_like_rid(type1):
318
- type1 = conn.get_records_by_id([type1])[0]['displayName']
318
+ type1 = conn.get_records_by_id([type1])[0]["displayName"]
319
319
  if looks_like_rid(type2):
320
- type2 = conn.get_records_by_id([type2])[0]['displayName']
320
+ type2 = conn.get_records_by_id([type2])[0]["displayName"]
321
321
 
322
322
  # Get type terms from observed variant
323
323
  terms1 = []
324
324
  if strict:
325
325
  try:
326
- terms1.append(get_term_by_name(conn, type1)['@rid'])
327
- except:
326
+ terms1.append(get_term_by_name(conn, type1)["@rid"])
327
+ except Exception:
328
328
  pass
329
329
  else:
330
330
  terms1 = get_terms_set(conn, [type1])
@@ -444,7 +444,7 @@ def compare_positional_variants(
444
444
  return False
445
445
 
446
446
  # Equivalent types
447
- if variant.get('type') and reference_variant.get('type'):
447
+ if variant.get("type") and reference_variant.get("type"):
448
448
  if not equivalent_types(conn, variant["type"], reference_variant["type"]):
449
449
  return False
450
450
 
@@ -10,6 +10,7 @@ import time
10
10
  from datetime import datetime
11
11
  from typing import Any, Dict, Iterable, List, Optional, Union, cast
12
12
  from urllib3.util.retry import Retry
13
+ from urllib.parse import urlsplit
13
14
 
14
15
  from pori_python.types import ParsedVariant, PositionalVariant, Record
15
16
 
@@ -112,6 +113,7 @@ class GraphKBConnection:
112
113
  )
113
114
  self.http.mount("https://", HTTPAdapter(max_retries=retries))
114
115
  self.token = ""
116
+ self.token_kc = ""
115
117
  self.url = url
116
118
  self.username = username
117
119
  self.password = password
@@ -126,9 +128,9 @@ class GraphKBConnection:
126
128
  @property
127
129
  def load(self) -> Optional[float]:
128
130
  if self.first_request and self.last_request:
129
- return (
130
- self.request_count * 1000 / millis_interval(self.first_request, self.last_request)
131
- )
131
+ msec = millis_interval(self.first_request, self.last_request)
132
+ if msec:
133
+ return self.request_count * 1000 / msec
132
134
  return None
133
135
 
134
136
  def request(self, endpoint: str, method: str = "GET", **kwargs) -> Dict:
@@ -213,12 +215,45 @@ class GraphKBConnection:
213
215
  """Convenience method for making post requests."""
214
216
  return self.request(uri, method="POST", data=json.dumps(data), **kwargs)
215
217
 
216
- def login(self, username: str, password: str) -> None:
218
+ def login_demo(self) -> None:
219
+ """
220
+ KBDEV-1328
221
+ GraphKB login in GSC's PORI online demo is done in 2 steps:
222
+ 1. get a first token from KeyCloak using username and password; self.login_demo()
223
+ 2. get a second token from the GraphKB API using keyCloakToken; self.login()
224
+ """
225
+ url_parts = urlsplit(self.url)
226
+ base_url = f"{url_parts.scheme}://{url_parts.netloc}"
227
+
228
+ try:
229
+ resp = requests.request(
230
+ url=f"{base_url}/auth/realms/PORI/protocol/openid-connect/token",
231
+ method="POST",
232
+ data={
233
+ "client_id": "GraphKB",
234
+ "grant_type": "password",
235
+ "password": self.password,
236
+ "username": self.username,
237
+ },
238
+ )
239
+ except Exception as err:
240
+ logger.debug(f"unable to fetch a token from KeyCloak: {err}")
241
+ raise err
242
+
243
+ resp.raise_for_status()
244
+ content = resp.json()
245
+ self.token_kc = content["access_token"]
246
+
247
+ def login(self, username: str, password: str, pori_demo: bool = False) -> None:
217
248
  self.username = username
218
249
  self.password = password
219
250
  connect_timeout = 7
220
251
  read_timeout = 61
221
252
 
253
+ # KBDEV-1328. Alt. GraphKB login for GSC's PORI online demo
254
+ if pori_demo or "pori-demo" in self.url:
255
+ self.login_demo()
256
+
222
257
  # use requests package directly to avoid recursion loop on login failure
223
258
  attempts = range(10)
224
259
  for attempt in attempts:
@@ -231,7 +266,12 @@ class GraphKBConnection:
231
266
  method="POST",
232
267
  headers=self.headers,
233
268
  timeout=(connect_timeout, read_timeout),
234
- data=json.dumps({"username": username, "password": password}),
269
+ data=json.dumps(
270
+ # KBDEV-1328. Alt. GraphKB login for GSC's PORI online demo
271
+ {"keyCloakToken": self.token_kc}
272
+ if self.token_kc
273
+ else {"username": username, "password": password}
274
+ ),
235
275
  )
236
276
  break
237
277
  except (requests.exceptions.ConnectionError, OSError) as err:
@@ -344,12 +344,12 @@ def annotate_signature_variants(
344
344
  # Keep support for 'high mutation burden' until statement datafix
345
345
  if (
346
346
  variant["signatureName"] == TMB_SIGNATURE
347
- and TMB_SIGNATURE != 'high mutation burden'
347
+ and TMB_SIGNATURE != "high mutation burden"
348
348
  ):
349
349
  matched_variants.extend(
350
350
  gkb_match.match_category_variant(
351
351
  graphkb_conn,
352
- 'high mutation burden',
352
+ "high mutation burden",
353
353
  variant["variantTypeName"],
354
354
  reference_class="Signature",
355
355
  )
@@ -381,7 +381,7 @@ def annotate_variants(
381
381
  disease_matches: List[str] = [],
382
382
  signature_variants: List[IprSignatureVariant] = [],
383
383
  small_mutations: List[IprSmallMutationVariant] = [],
384
- structural_variants: List[IprStructuralVariant] = [],
384
+ structural_variants: Sequence[IprStructuralVariant] = [],
385
385
  copy_variants: List[IprCopyVariant] = [],
386
386
  expression_variants: List[IprExprVariant] = [],
387
387
  ) -> List[Hashabledict]:
@@ -95,13 +95,34 @@ class IprConnection:
95
95
  )
96
96
 
97
97
  def upload_report(
98
- self, content: Dict, mins_to_wait: int = 5, async_upload: bool = False
98
+ self,
99
+ content: Dict,
100
+ mins_to_wait: int = 5,
101
+ async_upload: bool = False,
102
+ ignore_extra_fields: bool = False,
99
103
  ) -> Dict:
100
104
  if async_upload:
101
105
  # if async is used, the response for reports-async contains either 'jobStatus'
102
106
  # or 'report'. jobStatus is no longer available once the report is successfully
103
107
  # uploaded.
104
- initial_result = self.post("reports-async", content)
108
+
109
+ projects = self.get("project")
110
+ project_names = [item["name"] for item in projects]
111
+
112
+ # if project is not exist, create one
113
+ if content["project"] not in project_names:
114
+ logger.info(
115
+ f"Project not found - attempting to create project {content['project']}"
116
+ )
117
+ try:
118
+ self.post("project", {"name": content["project"]})
119
+ except Exception as err:
120
+ raise Exception(f"Project creation failed due to {err}")
121
+
122
+ if ignore_extra_fields:
123
+ initial_result = self.post("reports-async?ignore_extra_fields=true", content)
124
+ else:
125
+ initial_result = self.post("reports-async", content)
105
126
 
106
127
  report_id = initial_result["ident"]
107
128
 
@@ -158,7 +179,10 @@ class IprConnection:
158
179
 
159
180
  return current_status
160
181
  else:
161
- return self.post("reports", content)
182
+ if ignore_extra_fields:
183
+ return self.post("reports?ignore_extra_fields=true", content)
184
+ else:
185
+ return self.post("reports", content)
162
186
 
163
187
  def set_analyst_comments(self, report_id: str, data: Dict) -> Dict:
164
188
  """
@@ -212,3 +236,11 @@ class IprConnection:
212
236
  Get the current IPR spec, for the purposes of current report upload fields
213
237
  """
214
238
  return self.request("/spec.json", method="GET")
239
+
240
+ def validate_json(self, content: Dict) -> Dict:
241
+ """
242
+ Validate the provided json schema
243
+ """
244
+ result = self.post("reports/schema", content)
245
+ logger.info(f"{result['message']}")
246
+ return result
@@ -15,14 +15,14 @@ TMB_SIGNATURE_HIGH_THRESHOLD = (
15
15
  TMB_SIGNATURE_VARIANT_TYPE = "high signature"
16
16
  # Mapping micro-satellite from pipeline terms to GraphKB terms
17
17
  MSI_MAPPING = {
18
- 'microsatellite instability': { # MSI
19
- 'displayName': 'microsatellite instability high signature',
20
- 'signatureName': 'microsatellite instability',
21
- 'variantTypeName': 'high signature',
18
+ "microsatellite instability": { # MSI
19
+ "displayName": "microsatellite instability high signature",
20
+ "signatureName": "microsatellite instability",
21
+ "variantTypeName": "high signature",
22
22
  },
23
- 'microsatellite stable': { # MSS
24
- 'displayName': 'microsatellite stable signature present',
25
- 'signatureName': 'microsatellite stable',
26
- 'variantTypeName': 'signature present',
23
+ "microsatellite stable": { # MSS
24
+ "displayName": "microsatellite stable signature present",
25
+ "signatureName": "microsatellite stable",
26
+ "variantTypeName": "signature present",
27
27
  },
28
28
  }
@@ -257,7 +257,7 @@ def preprocess_copy_variants(rows: Iterable[Dict]) -> List[IprCopyVariant]:
257
257
  if chrom:
258
258
  # check that chr isn't already in the chrband;
259
259
  # this regex from https://vrs.ga4gh.org/en/1.2/terms_and_model.html#id25
260
- if chrband and (re.match("^cen|[pq](ter|([1-9][0-9]*(\.[1-9][0-9]*)?))$", chrband)):
260
+ if chrband and (re.match(r"^cen|[pq](ter|([1-9][0-9]*(\.[1-9][0-9]*)?))$", chrband)):
261
261
  if isinstance(chrom, int):
262
262
  chrom = str(chrom)
263
263
  chrom = chrom.strip("chr")
@@ -479,7 +479,7 @@ def preprocess_hla(rows: Iterable[Dict]) -> Iterable[Dict]:
479
479
 
480
480
 
481
481
  def preprocess_tmb(
482
- tmb_high: float, tmburMutationBurden: Dict = None, genomeTmb: str = None
482
+ tmb_high: float, tmburMutationBurden: Dict = {}, genomeTmb: float | str = ""
483
483
  ) -> Iterable[Dict]:
484
484
  """
485
485
  Process tumour mutation burden (tmb) input(s) into preformatted signature input.
@@ -495,7 +495,7 @@ def preprocess_tmb(
495
495
  tmbur_tmb_val = float(
496
496
  tmburMutationBurden["genomeIndelTmb"] + tmburMutationBurden["genomeSnvTmb"]
497
497
  )
498
- if genomeTmb == None:
498
+ if not genomeTmb and not isinstance(genomeTmb, float):
499
499
  logger.error(
500
500
  "backwards compatibility: deriving genomeTmb from tmburMutationBurden genomeIndelTmb + genomeSnvTmb"
501
501
  )
@@ -505,14 +505,16 @@ def preprocess_tmb(
505
505
 
506
506
  # genomeTmb
507
507
  # SDEV-4811 - mutation burden is now expected to be uploaded in genomeTmb as mutations/megabase
508
- if genomeTmb != None and genomeTmb != "":
508
+ if isinstance(genomeTmb, float):
509
+ tmb_val = genomeTmb
510
+ elif genomeTmb:
509
511
  try:
510
512
  tmb_val = float(genomeTmb)
511
513
  if tmburMutationBurden and tmbur_tmb_val != tmb_val:
512
514
  logger.warning(
513
515
  f"genomeTmb given {tmb_val} does not match tmburMutationBurden TMB {tmbur_tmb_val}"
514
516
  )
515
- except Exception as err:
517
+ except TypeError as err:
516
518
  logger.error(f"genomeTmb parsing failure {genomeTmb}: {err}")
517
519
 
518
520
  # comparaing tmb_val to threshold
@@ -520,7 +522,7 @@ def preprocess_tmb(
520
522
  if tmb_val >= tmb_high:
521
523
  return [
522
524
  {
523
- "displayName": f'{TMB_SIGNATURE} {TMB_SIGNATURE_VARIANT_TYPE}',
525
+ "displayName": f"{TMB_SIGNATURE} {TMB_SIGNATURE_VARIANT_TYPE}",
524
526
  "signatureName": TMB_SIGNATURE,
525
527
  "variantTypeName": TMB_SIGNATURE_VARIANT_TYPE,
526
528
  }
@@ -4,12 +4,15 @@ by other reporting systems
4
4
  """
5
5
 
6
6
  from __future__ import annotations
7
- from itertools import product
8
- from copy import copy
9
- from typing import Dict, Iterable, List, Sequence, Set, Tuple, cast
7
+
10
8
  import uuid
9
+ from copy import copy
10
+ from itertools import product
11
+ from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple, cast
12
+
11
13
  from pori_python.graphkb import GraphKBConnection
12
14
  from pori_python.graphkb import statement as gkb_statement
15
+ from pori_python.graphkb import util as gkb_util
13
16
  from pori_python.graphkb import vocab as gkb_vocab
14
17
  from pori_python.types import (
15
18
  Hashabledict,
@@ -18,12 +21,12 @@ from pori_python.types import (
18
21
  IprGene,
19
22
  IprVariant,
20
23
  KbMatch,
21
- Statement,
22
- Variant,
23
- KbVariantMatch,
24
24
  KbMatchedStatement,
25
25
  KbMatchedStatementConditionSet,
26
26
  KbMatchSections,
27
+ KbVariantMatch,
28
+ Statement,
29
+ Variant,
27
30
  )
28
31
 
29
32
  from .constants import GERMLINE_BASE_TERMS, VARIANT_CLASSES
@@ -612,7 +615,7 @@ def get_kb_statement_matched_conditions(
612
615
 
613
616
  def get_kb_matches_sections(
614
617
  gkb_matches: List[KbMatch] | List[Hashabledict],
615
- allow_partial_matches=False,
618
+ allow_partial_matches: bool = False,
616
619
  ) -> KbMatchSections:
617
620
  kb_variants = get_kb_variants(gkb_matches)
618
621
  kb_matched_statements = get_kb_matched_statements(gkb_matches)
@@ -627,25 +630,68 @@ def get_kb_matches_sections(
627
630
 
628
631
 
629
632
  def get_kb_disease_matches(
630
- graphkb_conn: GraphKBConnection, kb_disease_match: str = None, verbose: bool = True
633
+ graphkb_conn: GraphKBConnection,
634
+ kb_disease_match: Optional[str] = None,
635
+ verbose: bool = True,
636
+ useSubgraphsRoute: bool = True,
631
637
  ) -> list[str]:
632
638
 
639
+ disease_matches = []
640
+
633
641
  if not kb_disease_match:
634
- kb_disease_match = 'cancer'
642
+ kb_disease_match = "cancer"
635
643
  if verbose:
636
644
  logger.warning(f"No disease provided; will use '{kb_disease_match}'")
637
645
 
638
- if verbose:
639
- logger.info(f"Matching disease ({kb_disease_match}) to graphkb")
646
+ # Primary solution w/ subgraphs route
647
+ if useSubgraphsRoute:
648
+ if verbose:
649
+ logger.info(
650
+ f"Matching disease ({kb_disease_match}) to graphkb using 'subgraphs' API route."
651
+ )
640
652
 
641
- disease_matches = {
642
- r["@rid"]
643
- for r in gkb_vocab.get_term_tree(
644
- graphkb_conn,
645
- kb_disease_match,
646
- ontology_class="Disease",
653
+ try:
654
+ # KBDEV-1306
655
+ # Matching disease(s) from name, then tree traversal for ancestors & descendants.
656
+ # Leverage the new 'subgraphs' API route
657
+ base_records = gkb_util.convert_to_rid_list(
658
+ graphkb_conn.query(
659
+ gkb_vocab.query_by_name(
660
+ "Disease",
661
+ kb_disease_match,
662
+ )
663
+ )
664
+ )
665
+ if base_records:
666
+ response = graphkb_conn.post(
667
+ "/subgraphs/Disease",
668
+ {
669
+ "subgraphType": "tree",
670
+ "base": base_records,
671
+ },
672
+ )
673
+ disease_matches = list(response["result"]["g"]["nodes"].keys())
674
+
675
+ except Exception:
676
+ if verbose:
677
+ logger.info("Failed at using 'subgraphs' API route.")
678
+ useSubgraphsRoute = False
679
+
680
+ # Alternate solution w/ get_term_tree() -> 'similarTo' queryType route
681
+ # Traversal depth is limited
682
+ if not useSubgraphsRoute:
683
+ if verbose:
684
+ logger.info(f"Matching disease ({kb_disease_match}) to graphkb using get_term_tree()")
685
+ disease_matches = list(
686
+ {
687
+ r["@rid"]
688
+ for r in gkb_vocab.get_term_tree(
689
+ graphkb_conn,
690
+ kb_disease_match,
691
+ ontology_class="Disease",
692
+ )
693
+ }
647
694
  )
648
- }
649
695
 
650
696
  if not disease_matches:
651
697
  msg = f"failed to match disease ({kb_disease_match}) to graphkb"
@@ -653,4 +699,4 @@ def get_kb_disease_matches(
653
699
  logger.error(msg)
654
700
  raise ValueError(msg)
655
701
 
656
- return list(disease_matches)
702
+ return disease_matches