From c749d606d243beb8d0098e75ba5bf2f0e37d812a Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Fri, 13 Nov 2026 05:10:58 +0000 Subject: [PATCH] feat: add recursive option to ga4gh_identify ga4gh_identify() only identifies the object it is given. Contained identifiable objects (e.g. an Allele's SequenceLocation, or the members of a CisPhasedBlock) only get their digest stored as a side effect of serializing the parent, and never get an `id`. Callers that need every object to carry its ID, such as AnyVar storing received VRS objects, had to set each nested ID by hand or round-trip the object through vrs_enref()/vrs_deref(). Add a `recursive` keyword argument (default False, so existing behavior is unchanged). When it is True, ga4gh_identify() first walks all fields of the object depth-first, through lists, custom root types and non-identifiable objects such as TraversalBlock, and identifies every GA4GH identifiable object it finds. The same `in_place` option and use_ga4gh_compute_identifier_when context apply to contained objects. References given as CURIEs are left as is. As documented, `as_version` still ignores other parameters. Update the Basic Models notebook to identify the Allele and its location with a single recursive call. The rendered output is unchanged. Closes #596 --- .../getting_started/3_Basic_Models.ipynb | 5 +- src/ga4gh/core/identifiers.py | 52 +++++++ tests/test_vrs.py | 140 ++++++++++++++++++ 3 files changed, 194 insertions(+), 3 deletions(-) diff --git a/notebooks/getting_started/3_Basic_Models.ipynb b/notebooks/getting_started/3_Basic_Models.ipynb index e6310d84..8eb21389 100644 --- a/notebooks/getting_started/3_Basic_Models.ipynb +++ b/notebooks/getting_started/3_Basic_Models.ipynb @@ -271,7 +271,7 @@ }, "source": [ "#### Step 4 - Compute the identifiers\n", - "To make the *Allele* object a valid VRS object - that is that all identifiable objects have valid VRS identifiers - is to use the *ga4gh_identify* method on the identifiable objects (*SequenceLocation*, and *Allele*)." + "To make the *Allele* object a valid VRS object - that is that all identifiable objects have valid VRS identifiers - is to use the *ga4gh_identify* method on the identifiable objects (*SequenceLocation*, and *Allele*). With `recursive=True`, *ga4gh_identify* identifies every identifiable object contained in the *Allele* (here, the *SequenceLocation*) before identifying the *Allele* itself." ] }, { @@ -312,8 +312,7 @@ ], "source": [ "from ga4gh.core import ga4gh_identify\n", - "allele.location.id = ga4gh_identify(allele.location)\n", - "allele.id = ga4gh_identify(allele)\n", + "ga4gh_identify(allele, recursive=True)\n", "allele.model_dump(exclude_none=True)" ] }, diff --git a/src/ga4gh/core/identifiers.py b/src/ga4gh/core/identifiers.py index 07dfc3db..0320f860 100644 --- a/src/ga4gh/core/identifiers.py +++ b/src/ga4gh/core/identifiers.py @@ -17,6 +17,7 @@ import contextvars import re +from collections.abc import Iterator from contextlib import ContextDecorator from enum import Enum, IntEnum @@ -112,10 +113,37 @@ def is_ga4gh_identifier(ir: str) -> bool: return str(get_pydantic_root(ir)).startswith(NS_W_SEP) +def _iter_models(value: object) -> Iterator[BaseModel]: + """Yield the pydantic models in ``value``, which may be a model, a custom root + type wrapping a model, or a list or tuple of these. Other values yield nothing. + """ + value = get_pydantic_root(value) + if isinstance(value, BaseModel): + yield value + elif isinstance(value, list | tuple): + for item in value: + yield from _iter_models(item) + + +def _identify_contained(vro: BaseModel, in_place: str) -> None: + """Identify every GA4GH identifiable object contained in ``vro``, depth-first. + + All fields are searched, including those of non-identifiable objects (e.g. + the component of a TraversalBlock). ``vro`` itself is not identified. + """ + for field_name in type(vro).model_fields: + for obj in _iter_models(getattr(vro, field_name)): + _identify_contained(obj, in_place) + is_identifiable = getattr(obj, "is_ga4gh_identifiable", None) + if is_identifiable is not None and is_identifiable(): + ga4gh_identify(obj, in_place=in_place) + + def ga4gh_identify( vro, # noqa: ANN001 in_place: str = "default", as_version: PrevVrsVersion | None = None, + recursive: bool = False, ) -> str | None: """Return the GA4GH digest-based id for the object, as a CURIE (string). Returns None if object is not identifiable. @@ -130,6 +158,12 @@ def ga4gh_identify( - 'never': the vro.id field will not be edited in-place, even when empty + If ``recursive`` is ``True``, every GA4GH identifiable object contained in vro + (e.g. the location of an Allele, or the members of a CisPhasedBlock and their + locations) is identified first, depth-first, using the same ``in_place`` option + and use_ga4gh_compute_identifier_when context. This is done even if vro itself is + not identifiable. Contained objects given as references (CURIEs) are left as is. + If ``as_version`` is provided, other parameters are ignored and an identifier is returned following the conventions of the VRS version indicated by ``as_version_``. Raises ``ValueError`` if ``as_version`` is not a ``PrevVrsVersion``. @@ -145,9 +179,27 @@ def ga4gh_identify( ... ) >>> ga4gh_identify(location) 'ga4gh:SL.4t6JnYWqHwYw9WzBT_lmWBb3tLQNalkT' + + >>> allele = ga4gh.vrs.models.Allele( + ... location=ga4gh.vrs.models.SequenceLocation( + ... start=44908821, + ... end=44908822, + ... sequenceReference=ga4gh.vrs.models.SequenceReference( + ... refgetAccession="SQ.F-LrLMe1SRpfUZHkQmvkVKFEGaoDeHul" + ... ), + ... ), + ... state=ga4gh.vrs.models.LiteralSequenceExpression(sequence="T"), + ... ) + >>> ga4gh_identify(allele, recursive=True) + 'ga4gh:VA.zMPFEc3F_JAtk3BEHjYFzTcobYjWKFQn' + >>> allele.location.id + 'ga4gh:SL.4t6JnYWqHwYw9WzBT_lmWBb3tLQNalkT' """ PrevVrsVersion.validate(as_version) + if recursive and as_version is None: + _identify_contained(vro, in_place) + if vro.is_ga4gh_identifiable(): when_rule = ga4gh_compute_identifier_when.get(VrsObjectIdentifierIs.ANY) obj_id = None diff --git a/tests/test_vrs.py b/tests/test_vrs.py index 975854ab..8933d80a 100644 --- a/tests/test_vrs.py +++ b/tests/test_vrs.py @@ -2,6 +2,7 @@ from pydantic import ValidationError from ga4gh.core import ( + PrevVrsVersion, VrsObjectIdentifierIs, ga4gh_digest, ga4gh_identify, @@ -381,3 +382,142 @@ def test_compute_identifiers_when(): with use_ga4gh_compute_identifier_when(VrsObjectIdentifierIs.MISSING): assert ga4gh_identify(vo_a, in_place="never") == correct_id assert ga4gh_identify(vo_a, in_place="never") is correct_id + + +def test_ga4gh_identify_recursive(): + loc_id = "ga4gh:SL._G2K0qSioM74l_u3OaKR0mgLYdeTL7Xd" + allele_id = "ga4gh:VA.Hy2XU_-rp4IMh6I_1NXNecBo8Qx8n0oE" + + # not recursive: only the outermost object is identified + allele = models.Allele(**allele_dict) + assert ga4gh_identify(allele, in_place="always") == allele_id + assert allele.id == allele_id + assert allele.location.id is None + + # recursive: the location is identified too + allele = models.Allele(**allele_dict) + assert ga4gh_identify(allele, recursive=True) == allele_id + assert allele.id == allele_id + assert allele.location.id == loc_id + assert allele.location.digest == loc_id.split(".")[1] + + # in_place="never" computes the IDs without setting them + allele = models.Allele(**allele_dict) + assert ga4gh_identify(allele, in_place="never", recursive=True) == allele_id + assert allele.id is None + assert allele.location.id is None + + # in_place="default" keeps existing IDs, in_place="always" replaces them + other_loc_id = "ga4gh:SL.0123456789abcdef0123456789abcdef" + allele = models.Allele(**allele_dict) + allele.location.id = other_loc_id + assert ga4gh_identify(allele, recursive=True) == allele_id + assert allele.location.id == other_loc_id + assert ga4gh_identify(allele, in_place="always", recursive=True) == allele_id + assert allele.location.id == loc_id + + # the use_ga4gh_compute_identifier_when context applies to contained objects + allele = models.Allele(**allele_dict) + allele.location.id = other_loc_id + with use_ga4gh_compute_identifier_when(VrsObjectIdentifierIs.MISSING): + assert ga4gh_identify(allele, in_place="always", recursive=True) == allele_id + assert allele.location.id == other_loc_id + + # as_version ignores other parameters + allele = models.Allele(**allele_dict) + assert ( + ga4gh_identify(allele, as_version=PrevVrsVersion.V1_3, recursive=True) + == "ga4gh:VA.5Z7gWQGUuGAPe4Pw2_kJvnkhS2Q5jRhY" + ) + assert allele.id is None + assert allele.location.id is None + + +def test_ga4gh_identify_recursive_cpb(): + cpb = models.CisPhasedBlock( + members=[ + allele_383650_dict, + allele_417816_dict, + "ga4gh:VA.Hy2XU_-rp4IMh6I_1NXNecBo8Qx8n0oE", + ] + ) + cpb_id = ga4gh_identify(cpb, recursive=True) + assert cpb_id == cpb.id + assert cpb.model_dump(exclude_none=True) == { + "id": cpb_id, + "digest": cpb_id.split(".")[1], + "type": "CisPhasedBlock", + "members": [ + allele_383650_dict, + { + **allele_417816_dict, + "id": "ga4gh:VA.TKhpDsfclpSXpn6BjTLViB_ceqRerOd2", + "digest": "TKhpDsfclpSXpn6BjTLViB_ceqRerOd2", + "location": { + **allele_417816_dict["location"], + "id": "ga4gh:SL.KYxoEZ7E-frbN03t8K7e546-LJ-_NrKO", + "digest": "KYxoEZ7E-frbN03t8K7e546-LJ-_NrKO", + }, + }, + "ga4gh:VA.Hy2XU_-rp4IMh6I_1NXNecBo8Qx8n0oE", + ], + } + + +def test_ga4gh_identify_recursive_derivative_molecule(): + seq_ref = { + "type": "SequenceReference", + "refgetAccession": "SQ.F-LrLMe1SRpfUZHkQmvkVKFEGaoDeHul", + } + adjacency_dict = { + "type": "Adjacency", + "adjoinedSequences": [ + {"type": "SequenceLocation", "sequenceReference": seq_ref, "end": 1000}, + {"type": "SequenceLocation", "sequenceReference": seq_ref, "start": 2000}, + ], + } + terminus_dict = { + "type": "Terminus", + "location": { + "type": "SequenceLocation", + "sequenceReference": seq_ref, + "end": 3000, + }, + } + + # contained objects are found through non-identifiable objects + traversal_block = models.TraversalBlock(component=adjacency_dict) + assert ga4gh_identify(traversal_block, recursive=True) is None + adjacency = traversal_block.component + assert adjacency.id == ga4gh_identify( + models.Adjacency(**adjacency_dict), in_place="never" + ) + for loc, loc_dict in zip( + adjacency.adjoinedSequences, adjacency_dict["adjoinedSequences"], strict=True + ): + assert loc.id == ga4gh_identify( + models.SequenceLocation(**loc_dict), in_place="never" + ) + + dm_dict = { + "type": "DerivativeMolecule", + "components": [ + {"type": "TraversalBlock", "component": adjacency_dict}, + terminus_dict, + ], + } + dm = models.DerivativeMolecule(**dm_dict) + assert ga4gh_identify(dm, recursive=True) == dm.id + assert dm.id == ga4gh_identify( + models.DerivativeMolecule(**dm_dict), in_place="never" + ) + assert dm.components[0].component.model_dump(exclude_none=True) == ( + adjacency.model_dump(exclude_none=True) + ) + terminus = dm.components[1] + assert terminus.id == ga4gh_identify( + models.Terminus(**terminus_dict), in_place="never" + ) + assert terminus.location.id == ga4gh_identify( + models.SequenceLocation(**terminus_dict["location"]), in_place="never" + )