anyvar 1.0.0__tar.gz → 1.1.0.dev0__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 (131) hide show
  1. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/PKG-INFO +4 -2
  2. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/README.md +1 -0
  3. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/pyproject.toml +5 -9
  4. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/anyvar.py +15 -6
  5. anyvar-1.1.0.dev0/src/anyvar/core/metadata.py +57 -0
  6. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/mapping/liftover.py +2 -2
  7. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/main.py +13 -9
  8. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/objects_router.py +18 -3
  9. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/schema.py +28 -0
  10. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/search_router.py +16 -11
  11. anyvar-1.1.0.dev0/src/anyvar/restapi/translate_router.py +69 -0
  12. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/vcf_router.py +42 -17
  13. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/base.py +54 -6
  14. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/postgres.py +55 -32
  15. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/snowflake.py +55 -17
  16. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/translate/vrs_python.py +97 -3
  17. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/vcf/ingest.py +2 -0
  18. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar.egg-info/PKG-INFO +4 -2
  19. anyvar-1.1.0.dev0/src/anyvar.egg-info/SOURCES.txt +39 -0
  20. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar.egg-info/requires.txt +2 -1
  21. anyvar-1.0.0/.dockerignore +0 -33
  22. anyvar-1.0.0/.env.example +0 -42
  23. anyvar-1.0.0/.git-blame-ignore-revs +0 -3
  24. anyvar-1.0.0/.github/CODEOWNERS +0 -1
  25. anyvar-1.0.0/.github/ISSUE_TEMPLATE/bug-report.yaml +0 -93
  26. anyvar-1.0.0/.github/ISSUE_TEMPLATE/feature-request.yaml +0 -68
  27. anyvar-1.0.0/.github/labels.yml +0 -3
  28. anyvar-1.0.0/.github/workflows/labels.yml +0 -29
  29. anyvar-1.0.0/.github/workflows/python-package.yml +0 -133
  30. anyvar-1.0.0/.github/workflows/release.yml +0 -102
  31. anyvar-1.0.0/.github/workflows/stale.yml +0 -11
  32. anyvar-1.0.0/.gitignore +0 -126
  33. anyvar-1.0.0/.pre-commit-config.yaml +0 -21
  34. anyvar-1.0.0/.readthedocs.yaml +0 -16
  35. anyvar-1.0.0/.service_info_example.yaml +0 -14
  36. anyvar-1.0.0/CITATION.cff +0 -35
  37. anyvar-1.0.0/Dockerfile +0 -39
  38. anyvar-1.0.0/Makefile +0 -141
  39. anyvar-1.0.0/compose.yaml +0 -90
  40. anyvar-1.0.0/docs/Makefile +0 -20
  41. anyvar-1.0.0/docs/source/_templates/module_summary.rst +0 -8
  42. anyvar-1.0.0/docs/source/_templates/module_summary_no_inherit.rst +0 -9
  43. anyvar-1.0.0/docs/source/api/api/anyvar.anyvar.rst +0 -8
  44. anyvar-1.0.0/docs/source/api/api/anyvar.core.metadata.rst +0 -8
  45. anyvar-1.0.0/docs/source/api/api/anyvar.core.objects.rst +0 -8
  46. anyvar-1.0.0/docs/source/api/api/mapping/anyvar.mapping.liftover.rst +0 -8
  47. anyvar-1.0.0/docs/source/api/api/queueing/anyvar.queueing.celery_worker.rst +0 -8
  48. anyvar-1.0.0/docs/source/api/api/storage/anyvar.storage.base.rst +0 -9
  49. anyvar-1.0.0/docs/source/api/api/storage/anyvar.storage.mapper_registry.rst +0 -9
  50. anyvar-1.0.0/docs/source/api/api/storage/anyvar.storage.mappers.rst +0 -9
  51. anyvar-1.0.0/docs/source/api/api/storage/anyvar.storage.no_db.rst +0 -9
  52. anyvar-1.0.0/docs/source/api/api/storage/anyvar.storage.orm.rst +0 -9
  53. anyvar-1.0.0/docs/source/api/api/storage/anyvar.storage.postgres.rst +0 -9
  54. anyvar-1.0.0/docs/source/api/api/translate/anyvar.translate.base.rst +0 -8
  55. anyvar-1.0.0/docs/source/api/api/translate/anyvar.translate.vrs_python.rst +0 -8
  56. anyvar-1.0.0/docs/source/api/api/vcf/anyvar.vcf.ingest.rst +0 -8
  57. anyvar-1.0.0/docs/source/api/index.rst +0 -73
  58. anyvar-1.0.0/docs/source/changelog.rst +0 -7
  59. anyvar-1.0.0/docs/source/conf.py +0 -62
  60. anyvar-1.0.0/docs/source/configuration/async.rst +0 -99
  61. anyvar-1.0.0/docs/source/configuration/authentication.rst +0 -155
  62. anyvar-1.0.0/docs/source/configuration/docker_compose.rst +0 -156
  63. anyvar-1.0.0/docs/source/configuration/dotenv_example.rst +0 -4
  64. anyvar-1.0.0/docs/source/configuration/index.rst +0 -26
  65. anyvar-1.0.0/docs/source/configuration/logging.rst +0 -66
  66. anyvar-1.0.0/docs/source/configuration/service_info.rst +0 -23
  67. anyvar-1.0.0/docs/source/configuration/snowflake.rst +0 -97
  68. anyvar-1.0.0/docs/source/configuration/storage.rst +0 -41
  69. anyvar-1.0.0/docs/source/contributing.rst +0 -58
  70. anyvar-1.0.0/docs/source/features.rst +0 -74
  71. anyvar-1.0.0/docs/source/getting_started/docker_compose.rst +0 -46
  72. anyvar-1.0.0/docs/source/getting_started/index.rst +0 -14
  73. anyvar-1.0.0/docs/source/getting_started/manual_setup.rst +0 -100
  74. anyvar-1.0.0/docs/source/help.rst +0 -10
  75. anyvar-1.0.0/docs/source/index.rst +0 -26
  76. anyvar-1.0.0/docs/source/license.rst +0 -4
  77. anyvar-1.0.0/docs/source/usage/index.rst +0 -16
  78. anyvar-1.0.0/docs/source/usage/python.rst +0 -164
  79. anyvar-1.0.0/docs/source/usage/rest_api.rst +0 -189
  80. anyvar-1.0.0/docs/source/usage/rest_service.rst +0 -35
  81. anyvar-1.0.0/scripts/vcf_benchmark.py +0 -157
  82. anyvar-1.0.0/src/anyvar/core/metadata.py +0 -41
  83. anyvar-1.0.0/src/anyvar.egg-info/SOURCES.txt +0 -126
  84. anyvar-1.0.0/tests/__init__.py +0 -0
  85. anyvar-1.0.0/tests/conftest.py +0 -165
  86. anyvar-1.0.0/tests/data/service_info_openapi.yaml +0 -122
  87. anyvar-1.0.0/tests/data/variations.json +0 -510
  88. anyvar-1.0.0/tests/integration/restapi/conftest.py +0 -67
  89. anyvar-1.0.0/tests/integration/restapi/objects_router/test_annotation.py +0 -63
  90. anyvar-1.0.0/tests/integration/restapi/objects_router/test_location.py +0 -18
  91. anyvar-1.0.0/tests/integration/restapi/objects_router/test_mappings.py +0 -194
  92. anyvar-1.0.0/tests/integration/restapi/objects_router/test_variation.py +0 -196
  93. anyvar-1.0.0/tests/integration/restapi/test_search_router.py +0 -26
  94. anyvar-1.0.0/tests/integration/restapi/vcf_router/test_annotate_vcf.py +0 -383
  95. anyvar-1.0.0/tests/integration/restapi/vcf_router/test_ingest_vcf.py +0 -343
  96. anyvar-1.0.0/tests/unit/__init__.py +0 -0
  97. anyvar-1.0.0/tests/unit/mapping/__init__.py +0 -0
  98. anyvar-1.0.0/tests/unit/mapping/test_liftover.py +0 -234
  99. anyvar-1.0.0/tests/unit/restapi/__init__.py +0 -0
  100. anyvar-1.0.0/tests/unit/restapi/test_auth.py +0 -1031
  101. anyvar-1.0.0/tests/unit/restapi/test_meta_router.py +0 -65
  102. anyvar-1.0.0/tests/unit/restapi/test_schema.py +0 -14
  103. anyvar-1.0.0/tests/unit/storage/__init__.py +0 -0
  104. anyvar-1.0.0/tests/unit/storage/conftest.py +0 -35
  105. anyvar-1.0.0/tests/unit/storage/storage_test_funcs.py +0 -483
  106. anyvar-1.0.0/tests/unit/storage/test_no_db.py +0 -38
  107. anyvar-1.0.0/tests/unit/storage/test_postgres.py +0 -121
  108. anyvar-1.0.0/tests/unit/storage/test_snowflake.py +0 -107
  109. anyvar-1.0.0/tests/unit/storage/test_snowflake_dyntable.py +0 -128
  110. anyvar-1.0.0/tests/unit/test_anyvar.py +0 -43
  111. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/LICENSE +0 -0
  112. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/setup.cfg +0 -0
  113. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/__init__.py +0 -0
  114. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/core/__init__.py +0 -0
  115. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/core/objects.py +0 -0
  116. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/mapping/__init__.py +0 -0
  117. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/queueing/__init__.py +0 -0
  118. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/queueing/celery_worker.py +0 -0
  119. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/__init__.py +0 -0
  120. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/auth.py +0 -0
  121. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/restapi/meta_router.py +0 -0
  122. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/__init__.py +0 -0
  123. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/mapper_registry.py +0 -0
  124. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/mappers.py +0 -0
  125. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/no_db.py +0 -0
  126. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/storage/orm.py +0 -0
  127. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/translate/__init__.py +0 -0
  128. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/translate/base.py +0 -0
  129. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar/vcf/__init__.py +0 -0
  130. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar.egg-info/dependency_links.txt +0 -0
  131. {anyvar-1.0.0 → anyvar-1.1.0.dev0}/src/anyvar.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: anyvar
3
- Version: 1.0.0
3
+ Version: 1.1.0.dev0
4
4
  Summary: AnyVar provides Python and REST interfaces to validate, normalize, generate identifiers, and register biological sequence variation according to the GA4GH Variation Representation standards.
5
5
  Author-email: biocommons contributors <biocommons-dev@googlegroups.com>
6
6
  License: Apache License
@@ -223,7 +223,7 @@ License-File: LICENSE
223
223
  Requires-Dist: fastapi>=0.95.0
224
224
  Requires-Dist: python-multipart
225
225
  Requires-Dist: uvicorn
226
- Requires-Dist: ga4gh.vrs[extras]<3.0,>=2.2.0
226
+ Requires-Dist: ga4gh.vrs[extras]<3.0,>=2.3.1
227
227
  Requires-Dist: sqlalchemy~=2.0.0
228
228
  Requires-Dist: snowflake-sqlalchemy~=1.8.2
229
229
  Requires-Dist: pyyaml
@@ -232,6 +232,7 @@ Requires-Dist: pysam
232
232
  Requires-Dist: python-dotenv
233
233
  Requires-Dist: anyio
234
234
  Requires-Dist: bioutils
235
+ Requires-Dist: biocommons.seqrepo
235
236
  Provides-Extra: postgres
236
237
  Requires-Dist: psycopg[binary]; extra == "postgres"
237
238
  Provides-Extra: queueing
@@ -268,6 +269,7 @@ AnyVar enables **registration**, **lookup**, and **search** of genetic variants
268
269
  * Support a broad range of query modes, including VRS ID lookups, HGVS expressions, gene-based searches, and genomic ranges
269
270
  * Translate community nomenclatures and conventions into a universal model for variant representation
270
271
  * Provide a community-driven, extensible platform for shared conventions and policy to realize the above goals
272
+ * Enable institutions to deploy and manage their own variant registry to meet privacy, governance, or data-sharing requirements
271
273
 
272
274
  ## Information
273
275
 
@@ -6,6 +6,7 @@ AnyVar enables **registration**, **lookup**, and **search** of genetic variants
6
6
  * Support a broad range of query modes, including VRS ID lookups, HGVS expressions, gene-based searches, and genomic ranges
7
7
  * Translate community nomenclatures and conventions into a universal model for variant representation
8
8
  * Provide a community-driven, extensible platform for shared conventions and policy to realize the above goals
9
+ * Enable institutions to deploy and manage their own variant registry to meet privacy, governance, or data-sharing requirements
9
10
 
10
11
  ## Information
11
12
 
@@ -1,5 +1,6 @@
1
1
  [project]
2
2
  name = "anyvar"
3
+ version="1.1.0-dev0"
3
4
  authors = [
4
5
  { name="biocommons contributors", email="biocommons-dev@googlegroups.com" },
5
6
  ]
@@ -20,7 +21,7 @@ dependencies = [
20
21
  "fastapi>=0.95.0",
21
22
  "python-multipart", # required for fastapi file uploads
22
23
  "uvicorn",
23
- "ga4gh.vrs[extras]>=2.2.0,<3.0", # needs to be >=2.2.0 for RLE bug fix
24
+ "ga4gh.vrs[extras]>=2.3.1,<3.0",
24
25
  "sqlalchemy~=2.0.0",
25
26
  "snowflake-sqlalchemy~=1.8.2",
26
27
  "pyyaml",
@@ -28,9 +29,9 @@ dependencies = [
28
29
  "pysam",
29
30
  "python-dotenv",
30
31
  "anyio",
31
- "bioutils"
32
+ "bioutils",
33
+ "biocommons.seqrepo",
32
34
  ]
33
- dynamic = ["version"]
34
35
 
35
36
  [project.optional-dependencies]
36
37
  postgres = ["psycopg[binary]"]
@@ -72,17 +73,12 @@ Source = "https://github.com/biocommons/anyvar/"
72
73
 
73
74
 
74
75
  [build-system]
75
- requires = [
76
- "setuptools >= 65.3",
77
- "setuptools_scm >= 8"
78
- ]
76
+ requires = ["setuptools >= 65.3"]
79
77
  build-backend = "setuptools.build_meta"
80
78
 
81
79
  [tool.setuptools.package-data]
82
80
  "anyvar.storage" = ["*.sql"]
83
81
 
84
- [tool.setuptools_scm]
85
-
86
82
  [tool.pytest.ini_options]
87
83
  addopts = "--cov=anyvar --cov-report term-missing"
88
84
  testpaths = ["tests"]
@@ -240,27 +240,36 @@ class AnyVar:
240
240
  raise
241
241
 
242
242
  def get_object_mappings(
243
- self, source_object_id: str, mapping_type: metadata.VariationMappingType
243
+ self,
244
+ object_id: str,
245
+ mapping_type: metadata.VariationMappingType,
246
+ as_source: bool = True,
244
247
  ) -> Iterable[metadata.VariationMapping]:
245
248
  """Get all variation mappings given source object ID and mapping type
246
249
 
247
- :param source_object_id: ID of the source object
250
+ :param object_id: ID of the source object
248
251
  :param mapping_type: kind of mapping to retrieve
252
+ :param as_source: whether to retrieve mappings where ``object_id`` is the source
253
+ of the mapping, or the destination
249
254
  :return: iterable collection of mapping objects
250
255
  :raise ObjectNotFoundError: if ``source_object_id`` can't be found in DB
251
256
  """
252
257
  try:
253
- mappings = self.object_store.get_mappings(source_object_id, mapping_type)
258
+ mappings = self.object_store.get_mappings(
259
+ object_id,
260
+ as_source,
261
+ mapping_type,
262
+ )
254
263
  except Exception:
255
264
  _logger.exception(
256
265
  "Failed to retrieve mappings for source_object_id: %s and mapping_type: %s",
257
- source_object_id,
266
+ object_id,
258
267
  mapping_type,
259
268
  )
260
269
  raise
261
270
  if not mappings:
262
271
  try:
263
- _ = self.get_object(source_object_id)
272
+ _ = self.get_object(object_id)
264
273
  except KeyError as e:
265
- raise ObjectNotFoundError(source_object_id) from e
274
+ raise ObjectNotFoundError(object_id) from e
266
275
  return mappings
@@ -0,0 +1,57 @@
1
+ """Define types and classes for *metadata*, i.e. additional descriptions on top of stored objects.
2
+
3
+ This currently includes
4
+
5
+ * **Annotations**: free-text key-value descriptions of an object
6
+ * **Mappings**: directed associations between objects
7
+ """
8
+
9
+ from enum import StrEnum
10
+
11
+ from pydantic import BaseModel, JsonValue
12
+
13
+
14
+ class VariationMappingType(StrEnum):
15
+ """Supported mapping types between VRS Variations.
16
+
17
+ .. warning::
18
+
19
+ Currently, use of mappings outside of the liftover relation are experimental,
20
+ and these parameters are subject to change. The following describes current intentions,
21
+ and may or may not be validated within AnyVar.
22
+
23
+ * ``LIFTOVER_TO``: Genomic-to-genomic coordinate transformation. Use when mapping
24
+ a variation between two reference sequences of the same molecule type, typically
25
+ genomic DNA.
26
+ * ``TRANSCRIBE_TO``: Genomic-to-transcript (RNA/cDNA) projection. Use when projecting
27
+ a genomic DNA object onto a transcript sequence (RNA or cDNA). This accounts for
28
+ splicing, transcript strand orientation, and transcript-specific exon structure.
29
+ * ``TRANSLATE_TO``: Transcript-to-protein projection. This entails codon interpretation,
30
+ amino acid substitution/insertion/deletion/extension, and protein coordinate changes.
31
+ """
32
+
33
+ LIFTOVER_TO = "liftover_to"
34
+ TRANSCRIBE_TO = "transcribe_to"
35
+ TRANSLATE_TO = "translate_to"
36
+
37
+
38
+ class VariationMapping(BaseModel):
39
+ """Describe a mapping between two variations."""
40
+
41
+ source_id: str
42
+ dest_id: str
43
+ mapping_type: VariationMappingType
44
+
45
+
46
+ class AnnotationType(StrEnum):
47
+ """Describe commonly used annotation types"""
48
+
49
+ CREATION_TIMESTAMP = "creation_timestamp"
50
+
51
+
52
+ class Annotation(BaseModel):
53
+ """Generic annotation class which attaches any object to an identifier"""
54
+
55
+ object_id: str
56
+ annotation_type: str
57
+ annotation_value: JsonValue
@@ -247,14 +247,14 @@ def add_liftover_mapping(
247
247
  VariationMapping(
248
248
  source_id=input_vrs_id,
249
249
  dest_id=normalized_lifted_over_variant_id,
250
- mapping_type=VariationMappingType.LIFTOVER,
250
+ mapping_type=VariationMappingType.LIFTOVER_TO,
251
251
  )
252
252
  )
253
253
  storage.add_mapping(
254
254
  VariationMapping(
255
255
  source_id=normalized_lifted_over_variant_id,
256
256
  dest_id=input_vrs_id,
257
- mapping_type=VariationMappingType.LIFTOVER,
257
+ mapping_type=VariationMappingType.LIFTOVER_TO,
258
258
  )
259
259
  )
260
260
  return None
@@ -2,9 +2,9 @@
2
2
 
3
3
  import logging
4
4
  import logging.config
5
- import os
6
5
  import pathlib
7
6
  from contextlib import asynccontextmanager
7
+ from os import getenv
8
8
 
9
9
  import anyio
10
10
  import yaml
@@ -24,6 +24,7 @@ from anyvar.restapi.schema import (
24
24
  ServiceInfo,
25
25
  )
26
26
  from anyvar.restapi.search_router import search_router
27
+ from anyvar.restapi.translate_router import translate_router
27
28
  from anyvar.restapi.vcf_router import vcf_router
28
29
 
29
30
  load_dotenv()
@@ -34,7 +35,7 @@ _logger = logging.getLogger(__name__)
34
35
  async def app_lifespan(param_app: FastAPI): # noqa: ANN201
35
36
  """Perform resource initialization/teardown"""
36
37
  # Configure logging from file or use default
37
- logging_config_file = os.environ.get("ANYVAR_LOGGING_CONFIG", None)
38
+ logging_config_file = getenv("ANYVAR_LOGGING_CONFIG", None)
38
39
  if logging_config_file and pathlib.Path(logging_config_file).is_file():
39
40
  async with await anyio.open_file(logging_config_file) as f:
40
41
  try:
@@ -50,7 +51,7 @@ async def app_lifespan(param_app: FastAPI): # noqa: ANN201
50
51
  _logger.info("Logging with default configs.")
51
52
 
52
53
  # Override default service-info parameters
53
- service_info_config_file = os.environ.get("ANYVAR_SERVICE_INFO")
54
+ service_info_config_file = getenv("ANYVAR_SERVICE_INFO")
54
55
  if service_info_config_file and pathlib.Path(service_info_config_file).is_file():
55
56
  async with await anyio.open_file(service_info_config_file) as f:
56
57
  try:
@@ -83,11 +84,13 @@ async def app_lifespan(param_app: FastAPI): # noqa: ANN201
83
84
  storage.close()
84
85
 
85
86
 
87
+ API_PREFIX = getenv("ANYVAR_API_PREFIX", "")
88
+
86
89
  app = FastAPI(
87
90
  title="AnyVar",
88
91
  version=anyvar.__version__,
89
- docs_url="/",
90
- openapi_url="/openapi.json",
92
+ docs_url=f"{API_PREFIX}/",
93
+ openapi_url=f"{API_PREFIX}/openapi.json",
91
94
  swagger_ui_parameters={"tryItOutEnabled": True},
92
95
  description="Register and retrieve VRS value objects.",
93
96
  lifespan=app_lifespan,
@@ -95,7 +98,8 @@ app = FastAPI(
95
98
  )
96
99
 
97
100
 
98
- app.include_router(vcf_router, tags=[EndpointTag.VCF])
99
- app.include_router(search_router, tags=[EndpointTag.SEARCH])
100
- app.include_router(meta_router, tags=[EndpointTag.META])
101
- app.include_router(objects_router, tags=[EndpointTag.VRS_OBJECTS])
101
+ app.include_router(vcf_router, tags=[EndpointTag.VCF], prefix=API_PREFIX)
102
+ app.include_router(search_router, tags=[EndpointTag.SEARCH], prefix=API_PREFIX)
103
+ app.include_router(meta_router, tags=[EndpointTag.META], prefix=API_PREFIX)
104
+ app.include_router(translate_router, tags=[EndpointTag.TRANSLATE], prefix=API_PREFIX)
105
+ app.include_router(objects_router, tags=[EndpointTag.VRS_OBJECTS], prefix=API_PREFIX)
@@ -5,7 +5,7 @@ import logging
5
5
  from http import HTTPStatus
6
6
  from typing import Annotated, cast
7
7
 
8
- from fastapi import APIRouter, Body, HTTPException, Request, Response
8
+ from fastapi import APIRouter, Body, HTTPException, Query, Request, Response
9
9
  from fastapi.params import Path
10
10
  from fastapi.responses import JSONResponse, StreamingResponse
11
11
  from ga4gh.vrs.dataproxy import DataProxyValidationError
@@ -460,11 +460,19 @@ def add_object_mapping(
460
460
  )
461
461
 
462
462
 
463
+ _get_mappings_description = """Retrieve mappings associated with a VRS object.
464
+
465
+ Mappings are *directed*; if `as_source=true`, then retrieve mappings where the VRS object is the mapping *source*, i.e. where the mapping points from the object to another. Otherwise, get mappings where another object points to the VRS object.
466
+
467
+ By default, retrieve mappings of any type. Use the `mapping_type` argument to specify a specific type.
468
+ """
469
+
470
+
463
471
  @objects_router.get(
464
472
  "/object/{vrs_id}/mappings/{mapping_type}",
465
473
  response_model_exclude_none=True,
466
474
  summary="Retrieve mappings for a VRS Object",
467
- description="Retrieve mappings for a VRS Object by ID and mapping type",
475
+ description=_get_mappings_description,
468
476
  )
469
477
  def get_object_mapping(
470
478
  request: Request,
@@ -472,11 +480,18 @@ def get_object_mapping(
472
480
  mapping_type: Annotated[
473
481
  metadata.VariationMappingType, Path(..., description="Mapping type")
474
482
  ],
483
+ as_source: Annotated[
484
+ bool,
485
+ Query(
486
+ ...,
487
+ description="If `true`, get mappings where `vrs_id` corresponds to the mapping source; otherwise, get mappings where `vrs_id` is the mapping destination",
488
+ ),
489
+ ] = True,
475
490
  ) -> GetMappingResponse:
476
491
  """Retrieve mappings for a VRS Object."""
477
492
  av: AnyVar = request.app.state.anyvar
478
493
  try:
479
- mappings = av.get_object_mappings(vrs_id, mapping_type)
494
+ mappings = av.get_object_mappings(vrs_id, mapping_type, as_source)
480
495
  except ObjectNotFoundError as e:
481
496
  raise HTTPException(
482
497
  HTTPStatus.NOT_FOUND,
@@ -27,6 +27,7 @@ class EndpointTag(str, Enum):
27
27
  VCF = "VCF Operations"
28
28
  VRS_OBJECTS = "VRS Objects"
29
29
  SEARCH = "Search Operations"
30
+ TRANSLATE = "Translate Operations"
30
31
 
31
32
 
32
33
  class ServiceEnvironment(str, Enum):
@@ -296,6 +297,33 @@ class SearchResponse(BaseModel):
296
297
  """Describe response for the GET /search endpoint"""
297
298
 
298
299
  variations: list[models.Variation]
300
+ next_cursor: str | None
301
+
302
+
303
+ class TranslateToResponse(BaseModel):
304
+ """Describe response for the POST /translate_to endpoint"""
305
+
306
+ model_config = ConfigDict(
307
+ json_schema_extra={
308
+ "examples": [
309
+ {
310
+ "hgvs": [
311
+ "ENST00000453660.4:n.718G>T",
312
+ "ENSP00000483018.1:p.Gly229Val",
313
+ ],
314
+ "spdi": ["NC_000009.12:133256041:C:A"],
315
+ }
316
+ ],
317
+ }
318
+ )
319
+
320
+ identifiers: dict[str, list[str]]
321
+
322
+
323
+ class TranslateFromResponse(BaseModel):
324
+ """Describe response for the POST /translate_from endpoint"""
325
+
326
+ object: objects.VrsObject
299
327
 
300
328
 
301
329
  class RunStatusResponse(BaseModel):
@@ -36,6 +36,8 @@ def search_variations(
36
36
  int,
37
37
  Query(..., description="End position for genomic region", examples=[2781758]),
38
38
  ],
39
+ page_size: int = Query(1000, ge=1, le=10000),
40
+ cursor: str | None = Query(None, description="Opaque pagination cursor"),
39
41
  ) -> SearchResponse:
40
42
  """Perform genomic coordinate-based search over all registered variations."""
41
43
  av: AnyVar = request.app.state.anyvar
@@ -50,15 +52,18 @@ def search_variations(
50
52
  detail="Unable to dereference provided accession ID",
51
53
  ) from e
52
54
 
53
- alleles = []
54
- if ga4gh_id:
55
- try:
56
- refget_accession = ga4gh_id.split("ga4gh:")[-1]
57
- alleles = av.object_store.search_alleles(refget_accession, start, end)
58
- except NotImplementedError as e:
59
- raise HTTPException(
60
- status_code=HTTPStatus.NOT_IMPLEMENTED,
61
- detail="Search not implemented for current storage backend",
62
- ) from e
55
+ if not ga4gh_id:
56
+ return SearchResponse(variations=[], next_cursor=None)
63
57
 
64
- return SearchResponse(variations=alleles)
58
+ try:
59
+ refget_accession = ga4gh_id.split("ga4gh:")[-1]
60
+ page = av.object_store.search_alleles(
61
+ refget_accession, start, end, page_size=page_size, cursor=cursor
62
+ )
63
+ except NotImplementedError as e:
64
+ raise HTTPException(
65
+ status_code=HTTPStatus.NOT_IMPLEMENTED,
66
+ detail="Search not implemented for current storage backend",
67
+ ) from e
68
+
69
+ return SearchResponse(variations=page.items, next_cursor=page.next_cursor)
@@ -0,0 +1,69 @@
1
+ """Provide API routes relating to translate operations"""
2
+
3
+ from http import HTTPStatus
4
+ from typing import Annotated
5
+
6
+ from fastapi import APIRouter, HTTPException, Request
7
+ from fastapi.params import Path
8
+ from ga4gh.vrs.extras.translator import AlleleTranslator
9
+ from ga4gh.vrs.models import Allele
10
+ from pydantic import StrictStr
11
+
12
+ from anyvar.anyvar import AnyVar
13
+ from anyvar.restapi.schema import TranslateFromResponse, TranslateToResponse
14
+
15
+ translate_router = APIRouter()
16
+
17
+
18
+ @translate_router.post(
19
+ "/translate_to",
20
+ response_model_exclude_none=True,
21
+ operation_id="translateTo",
22
+ summary="Translate the specified VRS object to other identifiers",
23
+ description="Return a dictionary of variant identifiers keyed by identifier type (i.e. hgvs, spdi) that are represented by the specified VRS Allele object",
24
+ )
25
+ def translate_to(
26
+ request: Request,
27
+ vrs_object: Allele,
28
+ ) -> TranslateToResponse:
29
+ """Translate the specified VRS object to other identifiers"""
30
+ av: AnyVar = request.app.state.anyvar
31
+ translator: AlleleTranslator = av.translator.allele_tlr
32
+ try:
33
+ identifiers = {
34
+ fmt: translator.translate_to(vrs_object, fmt)
35
+ for fmt in translator.to_translators
36
+ }
37
+ except ValueError as e:
38
+ raise HTTPException(
39
+ status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
40
+ detail=str(e),
41
+ ) from e
42
+ return TranslateToResponse(identifiers=identifiers)
43
+
44
+
45
+ @translate_router.get(
46
+ "/translate_from/{fmt}/{identifier}",
47
+ response_model_exclude_none=True,
48
+ operation_id="translateFrom",
49
+ summary="Translate the specified identifier to a VRS Object",
50
+ description="Return the full VRS Object for the given variant identifier",
51
+ )
52
+ def translate_from(
53
+ request: Request,
54
+ fmt: Annotated[
55
+ StrictStr, Path(..., description="Format for identifier (i.e. hgvs, gnomad)")
56
+ ],
57
+ identifier: Annotated[StrictStr, Path(..., description="Identifier")],
58
+ ) -> TranslateFromResponse:
59
+ """Translate the specified identifier to a VRS Object"""
60
+ av: AnyVar = request.app.state.anyvar
61
+ translator: AlleleTranslator = av.translator.allele_tlr
62
+ try:
63
+ vrs_object = translator.translate_from(identifier, fmt)
64
+ except (ValueError, NotImplementedError) as e:
65
+ raise HTTPException(
66
+ status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
67
+ detail=str(e),
68
+ ) from e
69
+ return TranslateFromResponse(object=vrs_object)
@@ -55,6 +55,46 @@ _expected_vrs_ids_per_second = int(
55
55
  )
56
56
 
57
57
 
58
+ async def write_vcf_and_count_sites(
59
+ vcf: UploadFile, run_id: str | None, input_file_path: pathlib.Path
60
+ ) -> int:
61
+ """Write fastapi file buffer to a tmp location and get VCF site count
62
+
63
+ :param vcf: uploaded file from the FastAPI request
64
+ :param run_id: ID for the task, used for logging
65
+ :param input_file_path: location to write file to
66
+ :return: VCF site count
67
+ """
68
+ vcf_site_count = 0
69
+ newline = b"\n"
70
+ remainder = b""
71
+
72
+ async with aiofiles.open(input_file_path, mode="wb") as fd:
73
+ while chunk := await vcf.read(1024 * 1024):
74
+ await fd.write(chunk)
75
+
76
+ chunk = remainder + chunk
77
+ lines = chunk.split(newline)
78
+
79
+ # Last line may be incomplete — save it for next iteration
80
+ remainder = lines.pop()
81
+
82
+ # Count non-header lines
83
+ vcf_site_count += sum(
84
+ 1 for line in lines if line and not line.startswith(b"#")
85
+ )
86
+
87
+ # Handle final remainder if file doesn't end with newline
88
+ if remainder and not remainder.startswith(b"#"):
89
+ vcf_site_count += 1
90
+
91
+ _logger.debug(
92
+ "wrote working file for async run %s vcf to %s", run_id, input_file_path
93
+ )
94
+ _logger.debug("vcf site count of async run %s vcf is %s", run_id, vcf_site_count)
95
+ return vcf_site_count
96
+
97
+
58
98
  async def _annotate_vcf_async(
59
99
  response: Response,
60
100
  vcf: UploadFile,
@@ -106,16 +146,7 @@ async def _annotate_vcf_async(
106
146
  "writing working file for async run %s vcf to %s", run_id, input_file_path
107
147
  )
108
148
 
109
- vcf_site_count = 0
110
- newline_bytes = b"\n"
111
- async with aiofiles.open(input_file_path, mode="wb") as fd:
112
- while buffer := await vcf.read(1024 * 1024):
113
- vcf_site_count += buffer.count(newline_bytes)
114
- await fd.write(buffer)
115
- _logger.debug(
116
- "wrote working file for async run %s vcf to %s", run_id, input_file_path
117
- )
118
- _logger.debug("vcf site count of async run %s vcf is %s", run_id, vcf_site_count)
149
+ vcf_site_count = await write_vcf_and_count_sites(vcf, run_id, input_file_path)
119
150
 
120
151
  # submit async job
121
152
  task_result = celery_worker.annotate_vcf.apply_async(
@@ -380,13 +411,7 @@ async def _ingest_annotated_vcf_async(
380
411
  input_file_path.parent.mkdir(parents=True)
381
412
  _logger.debug("writing working file for async vcf to %s", input_file_path)
382
413
 
383
- vcf_site_count = 0
384
- async with aiofiles.open(input_file_path, mode="wb") as fd:
385
- while buffer := await vcf.read(1024 * 1024):
386
- vcf_site_count += buffer.count(b"\n")
387
- await fd.write(buffer)
388
- _logger.debug("wrote working file for async vcf to %s", input_file_path)
389
- _logger.debug("vcf site count of async vcf is %s", vcf_site_count)
414
+ vcf_site_count = await write_vcf_and_count_sites(vcf, run_id, input_file_path)
390
415
 
391
416
  task_result = celery_worker.ingest_annotated_vcf.apply_async(
392
417
  kwargs={
@@ -1,7 +1,10 @@
1
1
  """Provide PostgreSQL-based storage implementation."""
2
2
 
3
+ import base64
4
+ import json
3
5
  from abc import ABC, abstractmethod
4
6
  from collections.abc import Iterable
7
+ from dataclasses import dataclass
5
8
 
6
9
  from ga4gh.vrs import models as vrs_models
7
10
 
@@ -29,6 +32,18 @@ class InvalidSearchParamsError(StorageError):
29
32
  """Raise if search params violate specified logical constraints"""
30
33
 
31
34
 
35
+ @dataclass(frozen=True)
36
+ class AlleleSearchPage:
37
+ """Return object for implementing keyset pagination in allele search
38
+
39
+ Used in accordance with GA4GH pagination guidelines --
40
+ https://github.com/ga4gh/TASC/blob/main/recommendations/API%20pagination%20guide.md#token-based-pagination
41
+ """
42
+
43
+ items: list[vrs_models.Allele]
44
+ next_cursor: str | None
45
+
46
+
32
47
  class Storage(ABC):
33
48
  """Abstract base class for interacting with storage backends."""
34
49
 
@@ -122,14 +137,17 @@ class Storage(ABC):
122
137
  @abstractmethod
123
138
  def get_mappings(
124
139
  self,
125
- source_object_id: str,
140
+ object_id: str,
141
+ as_source: bool,
126
142
  mapping_type: metadata.VariationMappingType | None = None,
127
143
  ) -> Iterable[metadata.VariationMapping]:
128
- """Return an iterable of mappings from the source ID
144
+ """Return an iterable of mappings
129
145
 
130
146
  Optionally provide a type to filter results.
131
147
 
132
- :param source_object_id: ID of the source object
148
+ :param object_id: ID of object to get mappings for
149
+ :param as_source: If ``True``, object_id is treated as the source. If ``False``,
150
+ ``object_id`` is treated as the destination.
133
151
  :param mapping_type: The type of mapping to retrieve (defaults to `None` to
134
152
  retrieve all mappings for the source ID)
135
153
  :return: iterable collection of mapping descriptors (empty if no matching mappings exist)
@@ -168,19 +186,48 @@ class Storage(ABC):
168
186
  depended upon by another object
169
187
  """
170
188
 
189
+ @staticmethod
190
+ def _encode_search_cursor(start: int, allele_id: str) -> str:
191
+ """Create cursor for search
192
+
193
+ :param start: start value for next row
194
+ :param allele_id: ID for next row
195
+ :return: cursor to use to fetch next page
196
+ """
197
+ raw = json.dumps(
198
+ {"start": start, "id": allele_id}, separators=(",", ":")
199
+ ).encode()
200
+ return base64.urlsafe_b64encode(raw).decode()
201
+
202
+ @staticmethod
203
+ def _decode_search_cursor(cursor: str) -> tuple[int, str]:
204
+ """Decode cursor for getting next page during search
205
+
206
+ :param cursor: opaque key included with previous result
207
+ :return: start and ID values indicating the first row of the next page
208
+ """
209
+ raw = base64.urlsafe_b64decode(cursor.encode())
210
+ obj = json.loads(raw)
211
+ return int(obj["start"]), str(obj["id"])
212
+
171
213
  @abstractmethod
172
214
  def search_alleles(
173
215
  self,
174
216
  refget_accession: str,
175
217
  start: int,
176
218
  stop: int,
177
- ) -> list[vrs_models.Allele]:
219
+ page_size: int = 1000,
220
+ cursor: str | None = None,
221
+ ) -> AlleleSearchPage:
178
222
  """Find all Alleles that are located within the specified interval.
179
223
 
180
224
  The interval is the closed range [start, stop] on the sequence identified by
181
225
  the RefGet SequenceReference accession (`SQ.*`). Both `start` and `stop` are
182
226
  inclusive and represent inter-residue positions.
183
227
 
228
+ Uses keyset pagination, meaning that altering the page size while looping through
229
+ successive cursors will effectively nullify the search loop.
230
+
184
231
  Currently, any variation which overlaps the queried region is returned.
185
232
 
186
233
  Todo (see Issue #338):
@@ -194,7 +241,8 @@ class Storage(ABC):
194
241
  :param refget_accession: refget accession (e.g. `"SQ.IW78mgV5Cqf6M24hy52hPjyyo5tCCd86"`)
195
242
  :param start: Inclusive, inter-residue start position of the interval
196
243
  :param stop: Inclusive, inter-residue end position of the interval
197
- :return: a list of matching VRS alleles
244
+ :param page_size: Max # of results to return
245
+ :param cursor: Opaque key indicating start location for query in pagination
246
+ :return: Results page including variants and a cursor for next result page, if available
198
247
  :raise InvalidSearchParamsError: if above search param requirements are violated
199
-
200
248
  """