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
3 changes: 3 additions & 0 deletions src/ga4gh/core/identifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ class PrevVrsVersion(str, Enum):
"""Define prior VRS versions supported for digest and identifier computation."""

V1_3 = "1.3"
# VRS 2.0 normalization selected the largest valid repeat subunit length for
# reference-derived insertions; VRS 2.1 selects the smallest
V2_0 = "2.0"

@classmethod
def validate(cls, version: object) -> None:
Expand Down
97 changes: 90 additions & 7 deletions src/ga4gh/vrs/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,9 @@ def ga4gh_serialize_as_version(self, as_version: PrevVrsVersion) -> str:
raise ValueError(msg)
out.append(result)
return f'{{"interval":{{"end":{out[1]},"start":{out[0]},"type":"SequenceInterval"}},"sequence_id":"{self.sequenceReference.refgetAccession.split(".")[1]}","type":"SequenceLocation"}}'
if as_version == PrevVrsVersion.V2_0:
# SequenceLocation serialization is unchanged between VRS 2.0 and 2.1
return encode_canonical_json(self.ga4gh_serialize()).decode("utf-8")
msg = f"Received an unexpected value for `as_version`: {as_version}. MUST be an instance of `PrevVrsVersion`."
raise TypeError(msg)

Expand All @@ -789,7 +792,10 @@ class ga4gh(Ga4ghIdentifiableObject.ga4gh): # noqa: N801
"""Define GA4GH serialization metadata for this model."""

prefix = "SL"
priorPrefix = {PrevVrsVersion.V1_3.value: "VSL"} # noqa: N815
priorPrefix = { # noqa: N815
PrevVrsVersion.V1_3.value: "VSL",
PrevVrsVersion.V2_0.value: "SL",
}
inherent = ["end", "sequenceReference", "start", "type"]


Expand Down Expand Up @@ -877,6 +883,17 @@ class _VariationBase(Ga4ghIdentifiableObject, ABC):
expressions: list[Expression] | None = None


def _interval_value(pos: Range | int) -> int:
"""Return the coordinate of an int or indefinite Range ([None, v] / [v, None])"""
value: int | list[int | None] | None = get_pydantic_root(pos)
if isinstance(value, int):
return value
if not isinstance(value, list) or None not in value:
msg = f"Expected an int or indefinite Range coordinate, but got {value}"
raise ValueError(msg)
return next(v for v in value if v is not None)


class Allele(_VariationBase, BaseModelForbidExtra):
"""The state of a molecule at a `Location`."""

Expand All @@ -895,14 +912,27 @@ class Allele(_VariationBase, BaseModelForbidExtra):
def ga4gh_serialize_as_version(self, as_version: PrevVrsVersion) -> str:
"""Return a serialized string following the conventions for Allele serialization as defined in the VRS version specified by ``as_version``.

:raises ValueError: If the Allele cannot be serialized for ``as_version``. See
``_ga4gh_serialize_as_1_3`` and ``_ga4gh_serialize_as_2_0``.
"""
if as_version == PrevVrsVersion.V1_3:
return self._ga4gh_serialize_as_1_3()
if as_version == PrevVrsVersion.V2_0:
return self._ga4gh_serialize_as_2_0()
msg = f"Received an unexpected value for `as_version`: {as_version}. MUST be an instance of `PrevVrsVersion`."
raise TypeError(msg)

def _ga4gh_serialize_as_1_3(self) -> str:
"""Return a serialized string following VRS 1.3 Allele serialization.

:raises ValueError: If ``state`` is not a ``LiteralSequenceExpression`` or
``ReferenceLengthExpression``; ``state.sequence`` is null.

:param as_version: Prior VRS version to use.
:raises TypeError: If the requested version is unsupported.
:return: Serialization for the requested prior version.
"""
location_digest = self.location.compute_digest(as_version=as_version)
location_digest = self.location.compute_digest(as_version=PrevVrsVersion.V1_3)

if not isinstance(
self.state, LiteralSequenceExpression | ReferenceLengthExpression
Expand All @@ -915,16 +945,69 @@ def ga4gh_serialize_as_version(self, as_version: PrevVrsVersion) -> str:
if sequence is None:
raise ValueError("State sequence attribute must be defined.")

if as_version == PrevVrsVersion.V1_3:
return f'{{"location":"{location_digest}","state":{{"sequence":"{sequence}","type":"LiteralSequenceExpression"}},"type":"Allele"}}'
msg = f"Received an unexpected value for `as_version`: {as_version}. MUST be an instance of `PrevVrsVersion`."
raise TypeError(msg)
return f'{{"location":"{location_digest}","state":{{"sequence":"{sequence}","type":"LiteralSequenceExpression"}},"type":"Allele"}}'

def _ga4gh_serialize_as_2_0(self) -> str:
"""Return a serialized string following VRS 2.0 Allele serialization.

VRS 2.0 normalization selected the largest valid repeat subunit length for
reference-derived insertions (``ReferenceLengthExpression`` ``length`` greater
than the location span); VRS 2.1 selects the smallest. The valid lengths are the
multiples of the smallest that divide the insertion length and fit within the
span. All other states serialize the same in VRS 2.0 and 2.1.

This assumes ``repeatSubunitLength`` is the smallest valid subunit, as produced
by VRS 2.1 normalization. Verifying that requires the reference sequence, so only
inconsistencies detectable from the Allele alone raise an error.

Nested digests are recomputed rather than read from a cached ``digest``, and are
not stored on this Allele or its location.

:raises ValueError: If a ``ReferenceLengthExpression`` ``state`` is not on a
``SequenceLocation`` with int or indefinite Range coordinates, has a Range
``length``, or has a ``repeatSubunitLength`` that is not a factor of the
insertion length within the span
"""
state = self.state
if isinstance(state, ReferenceLengthExpression):
if not isinstance(self.location, SequenceLocation) or not isinstance(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These checks (and the _interval_value calls below) run before the insert_length > 0 test, so deletion and reference RLEs, which serialize the same in 2.0 and 2.1, can raise here. For example, an RLE with start=[5, 10], end=[12, 15], length=2, repeatSubunitLength=2 (normalize passes definite ranges through unchanged) raises Expected an int or indefinite Range coordinate, but got [12, 15] instead of returning the unchanged id.

Could the 2.0 adjustment be skipped (falling back to the regular serialization) whenever the state isn't an insertion, or when the location or length can't be interpreted, and only raise for an insertion that actually needs adjusting?

state.length, int
):
msg = "A VRS 2.0 `ReferenceLengthExpression` requires a `SequenceLocation` and an int `length`"
raise ValueError(msg)
ref_length = _interval_value(self.location.end) - _interval_value(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: for a circular location that wraps the origin (start > end), ref_length goes negative, multiples is empty, and the error says repeatSubunitLength N is inconsistent with ... a -X residue span, which is misleading. A clear "unsupported location" error, or falling back to the regular serialization, would be friendlier.

self.location.start
)
insert_length = state.length - ref_length
if insert_length > 0:
p = state.repeatSubunitLength
multiples = range(p, ref_length + 1, p) if p > 0 else []

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: no multiple larger than insert_length can divide it, so the upper bound could be min(ref_length, insert_length). As written, a 1-bp insertion into a very long repeat (e.g. a 1 Mb span) builds a list of about 1M ints and runs about 1M modulo checks per 2.0 id. That adds up in VCF-scale migrations. A generator with max(...) instead of building valid as a list would also avoid the allocation.

valid = [c for c in multiples if insert_length % c == 0]
if not valid:
msg = (
f"repeatSubunitLength {p} is inconsistent with a normalized "
f"insertion of {insert_length} residues into a {ref_length} "
"residue span"
)
raise ValueError(msg)
state = state.model_copy(update={"repeatSubunitLength": valid[-1]})
location = (
self.location.compute_digest(as_version=PrevVrsVersion.V2_0)
if isinstance(self.location, SequenceLocation)
else self.location.ga4gh_serialize()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When location is an iriReference, this branch uses iriReference.ga4gh_serialize(), which reduces it to the bare digest, while the normal 2.1 serialization keeps the full IRI string. So 2.0 and 2.1 ids differ even for alleles that aren't insertion RLEs.

For example, Allele(location="ga4gh:SL.shRADI_uRNo_P7bKGqD7Hrsw6iAkXciO", state=LiteralSequenceExpression(sequence="A")) gives ga4gh:VA.leDC4CJOAEKlExh8jbJgG3RpHWNDG9t0 normally but ga4gh:VA.MIMMIPRiwpVTR_8eU0yRvSG7xkzzMCmr with as_version="2.0". Since only insertion RLEs should change between versions, I think the 2.0 path should serialize the location the same way the regular path does.

)
return encode_canonical_json(
{"location": location, "state": state.ga4gh_serialize(), "type": self.type}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This builds the Allele serialization by hand rather than going through ga4gh_serialize / _recurse_ga4gh_serialize. That duplication is what causes the iriReference mismatch above, and it will drift silently if Allele's inherent fields or IRI handling change later. A simpler and more robust approach: make a copy of the Allele with the adjusted state (and the 2.0 location digest), then serialize it through the shared path. That way only the RLE subunit differs between versions.

).decode("utf-8")

class ga4gh(Ga4ghIdentifiableObject.ga4gh): # noqa: N801
"""Define GA4GH serialization metadata for this model."""

prefix = "VA"
priorPrefix = {PrevVrsVersion.V1_3.value: "VA"} # noqa: N815
priorPrefix = { # noqa: N815
PrevVrsVersion.V1_3.value: "VA",
PrevVrsVersion.V2_0.value: "VA",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lower priority since CisPhasedBlock is still draft: V2_0 is only added to Allele and SequenceLocation, but a CPB's id is built from its member Allele digests, so it also changes when a member is an insertion RLE. Right now ga4gh_identify(cpb, as_version="2.0") raises AttributeError: This class does not support prior version identifiers. Probably fine to defer, but worth a follow-up issue so 2.0 handling can be made generic (serializing members with their 2.0 digests) before CPB stabilizes.

}
inherent = ["location", "state", "type"]


Expand Down
19 changes: 12 additions & 7 deletions src/ga4gh/vrs/normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,8 @@ def _normalize_allele(
factors = _factor_gen(seed_length)
for cycle_length in factors:
if cycle_length > len_extended_ref:
continue
# factors are ascending, so all remaining factors are too long
break
cycle_start = len_extended_ref - cycle_length
if _is_valid_cycle(cycle_start, extended_ref_seq, extended_alt_seq):
_set_location_from_interval(
Expand Down Expand Up @@ -364,20 +365,24 @@ def denormalize_reference_length_expression(


def _factor_gen(n: int) -> Iterator[int]:
"""Yield all factors of an integer in descending order.
"""Yield all factors of an integer in ascending order.

The first factor that passes `_is_valid_cycle` becomes the ``repeatSubunitLength``,
so ascending order selects the smallest valid factor (VRS 2.1 normalization). VRS
2.0 selected the largest; see ``PrevVrsVersion.V2_0`` for computing 2.0 digests.

:param n: Positive integer to factor. Nonpositive inputs yield no values.
:return: Iterator yielding factors from largest to smallest.
:return: Iterator yielding factors from smallest to largest.
"""
lower_factors = []
upper_factors = []
i = 1
while i * i <= n:
if n % i == 0:
yield n // i
yield i
if n // i != i:
lower_factors.append(i)
upper_factors.append(n // i)
i += 1
yield from reversed(lower_factors)
yield from reversed(upper_factors)


def _define_rle_allele(
Expand Down
170 changes: 170 additions & 0 deletions tests/cassettes/test_normalize_rle_smallest_subunit.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
interactions:
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007183&end=1007183
response:
body:
string: ''
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007182&end=1007183
response:
body:
string: T
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007181&end=1007182
response:
body:
string: G
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007180&end=1007181
response:
body:
string: T
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007179&end=1007180
response:
body:
string: G
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007178&end=1007179
response:
body:
string: T
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007177&end=1007178
response:
body:
string: G
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007176&end=1007177
response:
body:
string: T
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007175&end=1007176
response:
body:
string: G
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007174&end=1007175
response:
body:
string: T
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007173&end=1007174
response:
body:
string: G
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007172&end=1007173
response:
body:
string: C
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007183&end=1007184
response:
body:
string: C
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.Ya6Rs7DHhDeg7YaOSg1EoNi3U_nQ9SvO?start=1007173&end=1007183
response:
body:
string: GTGTGTGTGT
headers: {}
status:
code: 200
message: OK
version: 1
7 changes: 4 additions & 3 deletions tests/extras/test_allele_translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@ def tlr(rest_dataproxy):
},
},
{
# single base expansion (9*A -> 11*A)
# two base expansion (9*A -> 11*A): subunit lengths 1 and 2 are both valid, and
# VRS 2.1 selects the smallest (VRS 2.0 selected 2)
"spdi": "NC_000001.11:236900409:AAAAAAAAA:AAAAAAAAAAA",
"gnomad": "1-236900410-A-AAA",
"expected_allele": {
Expand All @@ -272,7 +273,7 @@ def tlr(rest_dataproxy):
},
"state": {
"length": 11,
"repeatSubunitLength": 2,
"repeatSubunitLength": 1,
"sequence": "AAAAAAAAAAA",
"type": "ReferenceLengthExpression",
},
Expand Down Expand Up @@ -629,7 +630,7 @@ def test_to_spdi_with_ref(tlr) -> None:
},
"state": {
"length": 14,
"repeatSubunitLength": 2,
"repeatSubunitLength": 1,
"sequence": "TTTTTTTTTTTTTT",
"type": "ReferenceLengthExpression",
},
Expand Down
Loading
Loading