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.
Files changed (49) hide show
  1. pori_python/__init__.py +1 -0
  2. pori_python/graphkb/__init__.py +2 -0
  3. pori_python/graphkb/constants.py +220 -0
  4. pori_python/graphkb/genes.py +540 -0
  5. pori_python/graphkb/match.py +710 -0
  6. pori_python/graphkb/py.typed +0 -0
  7. pori_python/graphkb/statement.py +48 -0
  8. pori_python/graphkb/util.py +523 -0
  9. pori_python/graphkb/vocab.py +198 -0
  10. pori_python/ipr/__init__.py +0 -0
  11. pori_python/ipr/annotate.py +373 -0
  12. pori_python/ipr/connection.py +214 -0
  13. pori_python/ipr/constants.py +9 -0
  14. pori_python/ipr/inputs.py +593 -0
  15. pori_python/ipr/ipr.py +390 -0
  16. pori_python/ipr/main.py +512 -0
  17. pori_python/ipr/py.typed +0 -0
  18. pori_python/ipr/summary.py +412 -0
  19. pori_python/ipr/therapeutic_options.py +83 -0
  20. pori_python/ipr/util.py +173 -0
  21. pori_python/types.py +177 -0
  22. pori_python-0.1.0.dist-info/LICENSE +674 -0
  23. pori_python-0.1.0.dist-info/METADATA +151 -0
  24. pori_python-0.1.0.dist-info/RECORD +49 -0
  25. pori_python-0.1.0.dist-info/WHEEL +5 -0
  26. pori_python-0.1.0.dist-info/dependency_links.txt +1 -0
  27. pori_python-0.1.0.dist-info/entry_points.txt +2 -0
  28. pori_python-0.1.0.dist-info/top_level.txt +2 -0
  29. tests/__init__.py +0 -0
  30. tests/test_graphkb/__init__.py +0 -0
  31. tests/test_graphkb/data.py +78 -0
  32. tests/test_graphkb/test_genes.py +306 -0
  33. tests/test_graphkb/test_graphkb.py +32 -0
  34. tests/test_graphkb/test_match.py +662 -0
  35. tests/test_graphkb/test_statement.py +100 -0
  36. tests/test_graphkb/test_util.py +151 -0
  37. tests/test_graphkb/test_vocab.py +85 -0
  38. tests/test_ipr/__init__.py +0 -0
  39. tests/test_ipr/constants.py +3 -0
  40. tests/test_ipr/test_annotate.py +149 -0
  41. tests/test_ipr/test_connection.py +97 -0
  42. tests/test_ipr/test_inputs.py +295 -0
  43. tests/test_ipr/test_ipr.py +338 -0
  44. tests/test_ipr/test_main.py +154 -0
  45. tests/test_ipr/test_probe.py +72 -0
  46. tests/test_ipr/test_summary.py +157 -0
  47. tests/test_ipr/test_upload.py +274 -0
  48. tests/test_ipr/test_util.py +29 -0
  49. tests/test_ipr/util.py +9 -0
@@ -0,0 +1,710 @@
1
+ """
2
+ Functions which return Variants from GraphKB which match some input variant definition
3
+ """
4
+
5
+ from typing import Dict, List, Optional, Set, Union, cast
6
+
7
+ from pori_python.types import (
8
+ BasicPosition,
9
+ Ontology,
10
+ ParsedVariant,
11
+ PositionalVariant,
12
+ Record,
13
+ Variant,
14
+ )
15
+
16
+ from . import GraphKBConnection
17
+ from .constants import (
18
+ AMBIGUOUS_AA,
19
+ DEFAULT_NON_STRUCTURAL_VARIANT_TYPE,
20
+ INPUT_COPY_CATEGORIES,
21
+ INPUT_EXPRESSION_CATEGORIES,
22
+ POS_VARIANT_RETURN_PROPERTIES,
23
+ STRUCTURAL_VARIANT_SIZE_THRESHOLD,
24
+ STRUCTURAL_VARIANT_TYPES,
25
+ VARIANT_RETURN_PROPERTIES,
26
+ )
27
+ from .util import (
28
+ FeatureNotFoundError,
29
+ convert_to_rid_list,
30
+ logger,
31
+ looks_like_rid,
32
+ stringifyVariant,
33
+ )
34
+ from .vocab import get_equivalent_terms, get_term_tree, get_terms_set
35
+
36
+ FEATURES_CACHE: Set[str] = set()
37
+
38
+
39
+ def get_equivalent_features(
40
+ conn: GraphKBConnection,
41
+ gene_name: str,
42
+ ignore_cache: bool = False,
43
+ is_source_id: bool = False,
44
+ source: str = "",
45
+ source_id_version: str = "",
46
+ ) -> List[Ontology]:
47
+ """Match an equivalent list of features given some input feature name (or ID).
48
+
49
+ Args:
50
+ gene_name: the gene name to search features by
51
+ ignore_cache (bool, optional): bypass the cache to always force a new request
52
+ is_source_id: treat the gene_name as the gene ID from the source database (ex. ENSG001)
53
+ source_id_version: the version of the source_id
54
+ source: the name of the source database the gene definition is from (ex. ensembl)
55
+ Returns:
56
+ equivalent feature records
57
+
58
+ Example:
59
+ get_equivalent_features(conn, 'KRAS')
60
+
61
+ Example:
62
+ get_equivalent_features(conn, 'ENSG001', source='ensembl', is_source_id=True)
63
+
64
+ Example:
65
+ get_equivalent_features(conn, 'ENSG001', source='ensembl', source_id_version='1')
66
+
67
+ Example:
68
+ get_equivalent_features(conn, '#3:44')
69
+ """
70
+ if looks_like_rid(gene_name):
71
+ return cast(
72
+ List[Ontology],
73
+ conn.query(
74
+ {"target": [gene_name], "queryType": "similarTo"}, ignore_cache=ignore_cache
75
+ ),
76
+ )
77
+
78
+ filters: List[Dict] = []
79
+ if source:
80
+ filters.append({"source": {"target": "Source", "filters": {"name": source}}})
81
+
82
+ if gene_name.count(".") == 1 and gene_name.split(".")[-1].isnumeric():
83
+ # eg. ENSG00000133703.11 or NM_033360.4
84
+ logger.debug(
85
+ f"Assuming {gene_name} has a .version_format - ignoring the version for equivalent features"
86
+ )
87
+ gene_name = gene_name.split(".")[0]
88
+
89
+ if is_source_id or source_id_version:
90
+ filters.append({"sourceId": gene_name})
91
+ if source_id_version:
92
+ filters.append(
93
+ {"OR": [{"sourceIdVersion": source_id_version}, {"sourceIdVersion": None}]}
94
+ )
95
+ elif FEATURES_CACHE and gene_name.lower() not in FEATURES_CACHE and not ignore_cache:
96
+ return []
97
+ else:
98
+ filters.append({"OR": [{"sourceId": gene_name}, {"name": gene_name}]})
99
+
100
+ return cast(
101
+ List[Ontology],
102
+ conn.query(
103
+ {"target": {"target": "Feature", "filters": filters}, "queryType": "similarTo"},
104
+ ignore_cache=ignore_cache,
105
+ ),
106
+ )
107
+
108
+
109
+ def cache_missing_features(conn: GraphKBConnection) -> None:
110
+ """
111
+ Create a cache of features that exist to avoid repeatedly querying
112
+ for missing features
113
+ """
114
+ genes = cast(
115
+ List[Ontology],
116
+ conn.query({"target": "Feature", "returnProperties": ["name", "sourceId"], "neighbors": 0}),
117
+ )
118
+ for gene in genes:
119
+ if gene["name"]:
120
+ FEATURES_CACHE.add(gene["name"].lower())
121
+ if gene["sourceId"]:
122
+ FEATURES_CACHE.add(gene["sourceId"].lower())
123
+
124
+
125
+ def match_category_variant(
126
+ conn: GraphKBConnection,
127
+ gene_name: str,
128
+ category: str,
129
+ root_exclude_term: str = "",
130
+ gene_source: str = "",
131
+ gene_is_source_id: bool = False,
132
+ ignore_cache: bool = False,
133
+ ) -> List[Variant]:
134
+ """
135
+ Returns a list of variants matching the input variant
136
+
137
+ Args:
138
+ conn (GraphKBConnection): the graphkb connection object
139
+ gene_name (str): the name of the gene the variant is in reference to
140
+ category (str): the variant category (ex. copy loss)
141
+ gene_source: The source database the gene is defined by (ex. ensembl)
142
+ gene_is_source_id: Indicates the gene name(s) input should be treated as sourceIds not names
143
+ Raises:
144
+ FeatureNotFoundError: The gene could not be found in GraphKB
145
+
146
+ Returns:
147
+ Array.<dict>: List of variant records from GraphKB which match the input
148
+ """
149
+ # disambiguate the gene to find all equivalent representations
150
+ features = convert_to_rid_list(
151
+ get_equivalent_features(
152
+ conn,
153
+ gene_name,
154
+ source=gene_source,
155
+ is_source_id=gene_is_source_id,
156
+ ignore_cache=ignore_cache,
157
+ )
158
+ )
159
+
160
+ if not features:
161
+ raise FeatureNotFoundError(
162
+ f"unable to find the gene ({gene_name}) or any equivalent representations"
163
+ )
164
+
165
+ # get the list of terms that we should match
166
+ terms = convert_to_rid_list(
167
+ get_term_tree(conn, category, root_exclude_term, ignore_cache=ignore_cache)
168
+ )
169
+
170
+ if not terms:
171
+ raise ValueError(f"unable to find the term/category ({category}) or any equivalent")
172
+
173
+ # find the variant list
174
+ return cast(
175
+ List[Variant],
176
+ conn.query(
177
+ {
178
+ "target": {
179
+ "target": "CategoryVariant",
180
+ "filters": [
181
+ {"reference1": features, "operator": "IN"},
182
+ {"type": terms, "operator": "IN"},
183
+ ],
184
+ },
185
+ "queryType": "similarTo",
186
+ "edges": ["AliasOf", "DeprecatedBy", "CrossReferenceOf", "GeneralizationOf"],
187
+ "treeEdges": ["Infers"],
188
+ "returnProperties": VARIANT_RETURN_PROPERTIES,
189
+ },
190
+ ignore_cache=ignore_cache,
191
+ ),
192
+ )
193
+
194
+
195
+ def match_copy_variant(
196
+ conn: GraphKBConnection, gene_name: str, category: str, drop_homozygous: bool = False, **kwargs
197
+ ) -> List[Variant]:
198
+ """
199
+ Returns a list of variants matching the input variant
200
+
201
+ Args:
202
+ conn (GraphKBConnection): the graphkb connection object
203
+ gene_name (str): the name of the gene the variant is in reference to
204
+ category (str): the variant category (ex. copy loss)
205
+ drop_homozygous (bool): Drop homozygous matches from the result when true
206
+
207
+ Raises:
208
+ ValueError: The input copy category is not recognized
209
+
210
+ Returns:
211
+ List of variant records from GraphKB which match the input
212
+ """
213
+ if category not in INPUT_COPY_CATEGORIES.values():
214
+ raise ValueError(f"not a valid copy variant input category ({category})")
215
+
216
+ result = match_category_variant(
217
+ conn, gene_name, category, root_exclude_term="structural variant", **kwargs
218
+ )
219
+
220
+ if drop_homozygous:
221
+ return [row for row in result if row["zygosity"] != "homozygous"]
222
+ return result
223
+
224
+
225
+ def match_expression_variant(
226
+ conn: GraphKBConnection, gene_name: str, category: str, **kwargs
227
+ ) -> List[Variant]:
228
+ if category not in INPUT_EXPRESSION_CATEGORIES.values():
229
+ raise ValueError(f"not a valid expression variant input category ({category})")
230
+
231
+ return match_category_variant(
232
+ conn, gene_name, category, root_exclude_term="biological", **kwargs
233
+ )
234
+
235
+
236
+ def positions_overlap(
237
+ pos_record: BasicPosition, range_start: BasicPosition, range_end: Optional[BasicPosition] = None
238
+ ) -> bool:
239
+ """
240
+ Check if 2 Position records from GraphKB indicate an overlap
241
+
242
+ Note:
243
+ null values indicate not-specified or any
244
+
245
+ Args:
246
+ pos_record (dict): the record to compare
247
+ range_start (dict): the position record indicating the start of an uncertainty range
248
+ range_end (dict, optional): the position record indicating the end of an uncertainty range
249
+
250
+ Raises:
251
+ NotImplementedError: if a cytoband type position is given
252
+
253
+ Returns:
254
+ bool: True if the positions overlap
255
+ """
256
+ if pos_record.get("@class", "") == "CytobandPosition":
257
+ raise NotImplementedError(
258
+ "Position comparison for cytoband coordinates is not yet implemented"
259
+ )
260
+
261
+ pos = pos_record.get("pos", None)
262
+ if pos is None:
263
+ return True
264
+
265
+ start = range_start.get("pos", None)
266
+
267
+ if range_end:
268
+ end = range_end.get("pos", None)
269
+
270
+ if start is not None and pos < start:
271
+ return False
272
+ if end is not None and pos > end:
273
+ return False
274
+ return True
275
+ return start is None or pos == start
276
+
277
+
278
+ def compare_positional_variants(
279
+ variant: Union[PositionalVariant, ParsedVariant],
280
+ reference_variant: Union[PositionalVariant, ParsedVariant],
281
+ generic: bool = True,
282
+ ) -> bool:
283
+ """
284
+ Compare 2 variant records from GraphKB to determine if they are equivalent
285
+
286
+ Args:
287
+ variant: the input variant
288
+ reference_variant: the reference (matched) variant record
289
+ generic (bool, optional): also include the more generic variants
290
+
291
+ Returns:
292
+ bool: True if the records are equivalent
293
+ """
294
+
295
+ # If specific vs more-generic variants are not to be considered as equivalent,
296
+ # check if their stringify representation match and return True or False right away.
297
+ if not generic:
298
+ variant_str: str = stringifyVariant(
299
+ variant,
300
+ withRef=False, # Reference(s) will not be included in the string repr.
301
+ withRefSeq=False, # Reference sequence will not be included in the string repr.
302
+ )
303
+ reference_variant_str: str = stringifyVariant(
304
+ reference_variant,
305
+ withRef=False, # Reference(s) will not be included in the string repr.
306
+ withRefSeq=False, # Reference sequence will not be included in the string repr.
307
+ )
308
+ return variant_str == reference_variant_str
309
+
310
+ # For break1, check if positions are overlaping between the variant and the reference.
311
+ # Continue only if True.
312
+ if not positions_overlap(
313
+ cast(BasicPosition, variant["break1Start"]),
314
+ cast(BasicPosition, reference_variant["break1Start"]),
315
+ (
316
+ None
317
+ if "break1End" not in reference_variant
318
+ else cast(BasicPosition, reference_variant["break1End"])
319
+ ),
320
+ ):
321
+ return False
322
+
323
+ # For break2, check if positions are overlaping between the variant and the reference.
324
+ # Continue only if True or no break2.
325
+ # TODO: check for variant without break2 but reference_variant with one.
326
+ if variant.get("break2Start"):
327
+ if not reference_variant.get("break2Start"):
328
+ return False
329
+ if not positions_overlap(
330
+ cast(BasicPosition, variant["break2Start"]),
331
+ cast(BasicPosition, reference_variant["break2Start"]),
332
+ (
333
+ None
334
+ if "break2End" not in reference_variant
335
+ else cast(BasicPosition, reference_variant["break2End"])
336
+ ),
337
+ ):
338
+ return False
339
+
340
+ # If both variants have untemplated sequence,
341
+ # check for size and content.
342
+ if (
343
+ variant.get("untemplatedSeq", None) is not None
344
+ and reference_variant.get("untemplatedSeq", None) is not None
345
+ ):
346
+ if (
347
+ variant.get("untemplatedSeqSize", None) is not None
348
+ and reference_variant.get("untemplatedSeqSize", None) is not None
349
+ ):
350
+ if variant["untemplatedSeqSize"] != reference_variant["untemplatedSeqSize"]:
351
+ return False
352
+
353
+ if (
354
+ reference_variant["untemplatedSeq"] is not None
355
+ and variant["untemplatedSeq"] is not None
356
+ ):
357
+ if (
358
+ reference_variant["untemplatedSeq"] not in AMBIGUOUS_AA
359
+ and variant["untemplatedSeq"] not in AMBIGUOUS_AA
360
+ ):
361
+ if reference_variant["untemplatedSeq"].lower() != variant["untemplatedSeq"].lower():
362
+ return False
363
+ elif len(variant["untemplatedSeq"]) != len(reference_variant["untemplatedSeq"]):
364
+ return False
365
+
366
+ # If both variants have a reference sequence,
367
+ # check if they are the same.
368
+ if (
369
+ variant.get("refSeq", None) is not None
370
+ and reference_variant.get("refSeq", None) is not None
371
+ ):
372
+ if (
373
+ reference_variant["refSeq"] not in AMBIGUOUS_AA
374
+ and variant["refSeq"] not in AMBIGUOUS_AA
375
+ ):
376
+ if reference_variant["refSeq"].lower() != variant["refSeq"].lower(): # type: ignore
377
+ return False
378
+ elif len(variant["refSeq"]) != len(reference_variant["refSeq"]): # type: ignore
379
+ return False
380
+
381
+ return True
382
+
383
+
384
+ def type_screening(
385
+ conn: GraphKBConnection, parsed: ParsedVariant, updateStructuralTypes=False
386
+ ) -> str:
387
+ """
388
+ [KBDEV-1056]
389
+ Given a parsed variant notation, ensure that for some structural variant, type
390
+ (e.g. duplication, deletion, insertion, indel, copy number, inversion, etc.)
391
+ is only returned when the length of the variation meets a threshold,
392
+ otherwise 'mutation' is returned as default.
393
+
394
+ Args:
395
+ conn (GraphKBConnection): the graphkb connection object
396
+ parsed (ParsedVariant): the variant notation parsed as a dictionary by the API
397
+ updateStructuralTypes (boolean): if True the API is queried for an updated list
398
+ of terms, otherwise an hard-coded list is used
399
+
400
+ Returns:
401
+ A string describing the variation type
402
+
403
+ Example:
404
+ # structural variant type returned as 'mutation' IF length < threshold (50)
405
+ type_screening(conn, {
406
+ 'type': 'deletion',
407
+ 'break1Start': {'pos': 1},
408
+ 'break2Start': {'pos': 5},
409
+ }) -> 'mutation'
410
+
411
+ Example:
412
+ # structural variant type returned as-is IF length >= threshold (50)
413
+ type_screening(conn, {
414
+ 'type': 'deletion',
415
+ 'break1Start': {'pos': 1},
416
+ 'break2Start': {'pos': 50},
417
+ }) -> 'deletion'
418
+
419
+ Example:
420
+ # fusion & translocation always returned as-is
421
+ type_screening(conn, {'type': 'fusion'}) -> 'fusion'
422
+
423
+ Example:
424
+ # non structural always returned as-is
425
+ type_screening(conn, {'type': 'substitution'}) -> 'substitution'
426
+ """
427
+ default_type = DEFAULT_NON_STRUCTURAL_VARIANT_TYPE
428
+ structuralVariantTypes = STRUCTURAL_VARIANT_TYPES
429
+ threshold = STRUCTURAL_VARIANT_SIZE_THRESHOLD
430
+
431
+ # Will use either hardcoded type list or an updated list from the API
432
+ if updateStructuralTypes:
433
+ rids = list(get_terms_set(conn, ["structural variant"]))
434
+ records = conn.get_records_by_id(rids)
435
+ structuralVariantTypes = [el["name"] for el in records]
436
+
437
+ # Unambiguous non-structural variation type
438
+ if parsed["type"] not in structuralVariantTypes:
439
+ return parsed["type"]
440
+
441
+ # Unambiguous structural variation type
442
+ if parsed["type"] in ["fusion", "translocation"]:
443
+ return parsed["type"]
444
+ if parsed.get("reference2", None):
445
+ return parsed["type"]
446
+ prefix = parsed.get("prefix", "g")
447
+ if prefix == "y": # Assuming all variations using cytoband coordiantes meet the size threshold
448
+ return parsed["type"]
449
+
450
+ # When size cannot be determined: exonic and intronic coordinates
451
+ # e.g. "MET:e.14del" meaning "Any deletion occuring at the 14th exon"
452
+ if prefix in ["e", "i"]: # Assuming they don't meet the size threshold
453
+ return default_type
454
+
455
+ # When size is given
456
+ if (parsed.get("untemplatedSeqSize") or 0) >= threshold:
457
+ return parsed["type"]
458
+
459
+ # When size needs to be computed from positions
460
+ pos_start: int = parsed.get("break1Start", {}).get("pos", 1) # type: ignore
461
+ pos_end: int = parsed.get("break2Start", {}).get("pos", pos_start) # type: ignore
462
+ pos_size = 3 if prefix == "p" else 1
463
+ if ((pos_end - pos_start) + 1) * pos_size >= threshold:
464
+ return parsed["type"]
465
+
466
+ # Default
467
+ return default_type
468
+
469
+
470
+ def match_positional_variant(
471
+ conn: GraphKBConnection,
472
+ variant_string: str,
473
+ reference1: Optional[str] = None,
474
+ reference2: Optional[str] = None,
475
+ gene_is_source_id: bool = False,
476
+ gene_source: str = "",
477
+ ignore_cache: bool = False,
478
+ updateStructuralTypes: bool = False,
479
+ ) -> List[Variant]:
480
+ """
481
+ Given the HGVS+ representation of some positional variant, parse it and match it to
482
+ annotations in GraphKB
483
+
484
+ Args:
485
+ variant_string: the HGVS+ annotation string
486
+ reference1: Explicitly specify the first reference link record (gene1)
487
+ reference2: Explicitly specify the second reference link record (gene2)
488
+ gene_source: The source database the gene is defined by (ex. ensembl)
489
+ gene_is_source_id: Indicates the gene name(s) input should be treated
490
+ as sourceIds not names
491
+ updateStructuralTypes: Whether or not updating the structural variant list
492
+ with an API call, or use the hard-coded one
493
+
494
+ Raises:
495
+ NotImplementedError: thrown for uncertain position input (ranges)
496
+ FeatureNotFoundError: One of the genes does not exist in GraphKB
497
+ ValueError: the gene names were given both in the variant_string and explicitly
498
+
499
+ Returns:
500
+ A list of matched statement records
501
+
502
+ Example:
503
+ match_positional_variant(conn, '(EWSR1,FLI1):fusion(e.1,e.2)')
504
+
505
+ Example:
506
+ match_positional_variant(conn, 'fusion(e.1,e.2)', 'EWSR1', 'FLI1')
507
+
508
+ Example:
509
+ match_positional_variant(conn, 'fusion(e.1,e.2)', '#3:4', '#4:5')
510
+
511
+ Example:
512
+ match_positional_variant(conn, 'fusion(e.1,e.2)', '123', '456', gene_is_source_id=True, gene_source='entrez gene')
513
+
514
+ Example:
515
+ match_positional_variant(conn, 'KRAS:p.G12D')
516
+
517
+ Example:
518
+ match_positional_variant(conn, 'p.G12D', 'KRAS')
519
+ """
520
+ # parse the representation
521
+ parsed = conn.parse(variant_string, not (reference1 or reference2))
522
+
523
+ if "break1End" in parsed or "break2End" in parsed: # uncertain position
524
+ raise NotImplementedError(
525
+ f"Matching does not support uncertain positions ({variant_string}) as input"
526
+ )
527
+ if reference2 and not reference1:
528
+ raise ValueError("cannot specify reference2 without reference1")
529
+ # disambiguate the gene name
530
+ if reference1:
531
+ gene1 = reference1
532
+ if "reference1" in parsed:
533
+ raise ValueError(
534
+ "Cannot specify reference1 explicitly as well as in the variant notation"
535
+ )
536
+ else:
537
+ gene1 = parsed["reference1"]
538
+
539
+ gene1_features = get_equivalent_features(
540
+ conn, gene1, source=gene_source, is_source_id=gene_is_source_id, ignore_cache=ignore_cache
541
+ )
542
+ features = convert_to_rid_list(gene1_features)
543
+
544
+ if not features:
545
+ raise FeatureNotFoundError(
546
+ f"unable to find the gene ({gene1}) or any equivalent representations"
547
+ )
548
+
549
+ secondary_features = None
550
+
551
+ gene2: Optional[str] = None
552
+ if reference2:
553
+ gene2 = reference2
554
+ if "reference2" in parsed:
555
+ raise ValueError(
556
+ "Cannot specify reference2 explicitly as well as in the variant notation"
557
+ )
558
+ elif "reference1" in parsed:
559
+ raise ValueError(
560
+ "variant notation cannot contain features when explicit features are given"
561
+ )
562
+ elif (
563
+ "reference2" in parsed
564
+ and parsed.get("reference2", "?") != "?"
565
+ and parsed["reference2"] is not None
566
+ ):
567
+ gene2 = parsed["reference2"]
568
+
569
+ if gene2:
570
+ gene2_features = get_equivalent_features(
571
+ conn,
572
+ gene2,
573
+ source=gene_source,
574
+ is_source_id=gene_is_source_id,
575
+ ignore_cache=ignore_cache,
576
+ )
577
+ secondary_features = convert_to_rid_list(gene2_features)
578
+ if not secondary_features:
579
+ raise FeatureNotFoundError(
580
+ f"unable to find the gene ({gene2}) or any equivalent representations"
581
+ )
582
+
583
+ # match the existing mutations (positional)
584
+ query_filters = [
585
+ {"reference1": features},
586
+ {"reference2": secondary_features},
587
+ {"break1Start.@class": parsed["break1Start"]["@class"]},
588
+ ]
589
+
590
+ filtered_similarOnly: List[Record] = [] # For post filter match use
591
+ filtered_similarAndGeneric: List[Record] = [] # To be added to the matches at the very end
592
+
593
+ for row in cast(
594
+ List[Record],
595
+ conn.query(
596
+ {"target": "PositionalVariant", "filters": query_filters}, ignore_cache=ignore_cache
597
+ ),
598
+ ):
599
+ # TODO: Check if variant and reference_variant should be interchanged
600
+ if compare_positional_variants(
601
+ variant=parsed, reference_variant=cast(PositionalVariant, row), generic=True
602
+ ):
603
+ filtered_similarAndGeneric.append(row)
604
+ if compare_positional_variants(
605
+ variant=parsed,
606
+ reference_variant=cast(PositionalVariant, row),
607
+ generic=False, # Similar variants only
608
+ ):
609
+ filtered_similarOnly.append(row)
610
+
611
+ # post filter matches
612
+ matches: List[Record] = []
613
+ if filtered_similarOnly:
614
+ matches.extend(
615
+ conn.query(
616
+ {
617
+ "target": convert_to_rid_list(filtered_similarOnly),
618
+ "queryType": "similarTo",
619
+ "edges": ["AliasOf", "DeprecatedBy", "CrossReferenceOf", "GeneralizationOf"],
620
+ "treeEdges": ["Infers"],
621
+ "returnProperties": POS_VARIANT_RETURN_PROPERTIES,
622
+ },
623
+ ignore_cache=ignore_cache,
624
+ )
625
+ )
626
+
627
+ # screening type for discrepancies regarding structural variants
628
+ screened_type = type_screening(conn, parsed, updateStructuralTypes)
629
+
630
+ # disambiguate the variant type
631
+ variant_types_details = get_equivalent_terms(
632
+ conn,
633
+ screened_type,
634
+ root_exclude_term="mutation" if secondary_features else "",
635
+ ignore_cache=ignore_cache,
636
+ )
637
+
638
+ types = convert_to_rid_list(variant_types_details)
639
+
640
+ matches.extend(
641
+ conn.query(
642
+ {
643
+ "target": {
644
+ "target": "CategoryVariant",
645
+ "filters": [
646
+ {"reference1": features},
647
+ {"type": types},
648
+ {"reference2": secondary_features},
649
+ ],
650
+ },
651
+ "queryType": "similarTo",
652
+ "edges": ["AliasOf", "DeprecatedBy", "CrossReferenceOf"],
653
+ "treeEdges": ["Infers"],
654
+ "returnProperties": POS_VARIANT_RETURN_PROPERTIES,
655
+ },
656
+ ignore_cache=ignore_cache,
657
+ )
658
+ )
659
+
660
+ def cat_variant_query(
661
+ cat_features: List[str],
662
+ cat_types: List[str],
663
+ cat_secondary_features: Optional[List[str]] = None,
664
+ ) -> None:
665
+ matches.extend(
666
+ conn.query(
667
+ {
668
+ "target": {
669
+ "target": "CategoryVariant",
670
+ "filters": [
671
+ {"reference1": cat_features},
672
+ {"type": cat_types},
673
+ {"reference2": cat_secondary_features},
674
+ ],
675
+ },
676
+ "queryType": "similarTo",
677
+ "edges": ["AliasOf", "DeprecatedBy", "CrossReferenceOf"],
678
+ "treeEdges": [],
679
+ "returnProperties": VARIANT_RETURN_PROPERTIES,
680
+ },
681
+ ignore_cache=ignore_cache,
682
+ )
683
+ )
684
+
685
+ cat_variant_query(features, types, secondary_features)
686
+
687
+ if secondary_features:
688
+ # match single gene fusions for either gene
689
+ cat_variant_query(features, types, None)
690
+ cat_variant_query(secondary_features, types, None)
691
+
692
+ # Adding back generic PositionalVariant to the matches
693
+ if filtered_similarAndGeneric:
694
+ matches.extend(
695
+ conn.query(
696
+ {
697
+ "target": convert_to_rid_list(filtered_similarAndGeneric),
698
+ "queryType": "descendants",
699
+ "edges": [],
700
+ "returnProperties": POS_VARIANT_RETURN_PROPERTIES,
701
+ },
702
+ ignore_cache=ignore_cache,
703
+ )
704
+ )
705
+
706
+ result: Dict[str, Variant] = {}
707
+ for row in matches:
708
+ result[row["@rid"]] = cast(Variant, row)
709
+
710
+ return list(result.values())