Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions notebooks/getting_started/3_Basic_Models.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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."
]
},
{
Expand Down Expand Up @@ -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)"
]
},
Expand Down
52 changes: 52 additions & 0 deletions src/ga4gh/core/identifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import contextvars
import re
from collections.abc import Iterator
from contextlib import ContextDecorator
from enum import Enum, IntEnum

Expand Down Expand Up @@ -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.
Expand All @@ -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``.
Expand All @@ -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
Expand Down
140 changes: 140 additions & 0 deletions tests/test_vrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from pydantic import ValidationError

from ga4gh.core import (
PrevVrsVersion,
VrsObjectIdentifierIs,
ga4gh_digest,
ga4gh_identify,
Expand Down Expand Up @@ -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"
)
Loading