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
19 changes: 18 additions & 1 deletion src/ga4gh/vrs/extras/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,24 @@ def _from_gnomad(self, gnomad_expr: str, **kwargs) -> models.Allele | None:
return self._create_allele(values, **kwargs)

def _from_hgvs(self, hgvs_expr: str, **kwargs) -> models.Allele | None:
allele_values = self.hgvs_tools.extract_allele_values(hgvs_expr)
"""Parse HGVS expression into VRS Allele

kwargs:
require_validation (bool): If `True` then validation checks must pass in
order to return a VRS object. A `DataProxyValidationError` will be
raised if validation checks fail. If `False` then VRS object will be
returned even if validation checks fail. Defaults to `True`.
rle_seq_limit Optional(int): If RLE is set as the new state after
normalization, this sets the limit for the length of the `sequence`.
To exclude `sequence` from the response, set to 0.
For no limit, set to `None`.
Defaults value set in instance variable, `rle_seq_limit`.
do_normalize (bool): `True` if fully justified normalization should be
performed. `False` otherwise. Defaults to `True`
"""
allele_values = self.hgvs_tools.extract_allele_values(
hgvs_expr, require_validation=kwargs.get("require_validation", True)
)
if allele_values:
return self._create_allele(allele_values, **kwargs)
return None
Expand Down
72 changes: 70 additions & 2 deletions src/ga4gh/vrs/utils/hgvs_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@
_logger = logging.getLogger(__name__)


def _reference_bases(ref: object) -> str | None:

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: hgvs already has edit.ref_s ("returns ref if it smells like a sequence"), which treats digit-only refs the same way. Reusing it (with whatever U/N handling we settle on) would keep a single definition of "stated reference" and less code to maintain. As it stands, _reference_bases and ref_s disagree on lowercase and RNA refs, which is part of what causes the r. mismatch noted above.

"""Return stated reference bases, ignoring a length stored in ``edit.ref``.

HGVS keeps a deletion length there for expressions such as ``del1`` and
``del1insAT`` (``ref`` is ``"1"`` and ``ref_s`` is unset). Digits are not a
sequence. The hgvs validator skips them the same way.
"""
if not isinstance(ref, str) or not ref:
return None
try:
int(ref)
except ValueError:
return ref
return None


class HgvsTools:
"""A convenience class that exposes only the tools needed by vrs-python for working with HGVS (Human Genome Variation Society) notation.

Expand All @@ -40,6 +56,13 @@ def __init__(self, data_proxy: _DataProxy | None = None) -> None:
self.uta_conn = hgvs.dataproviders.uta.connect()
self.normalizer = hgvs.normalizer.Normalizer(self.uta_conn, validate=True)
self.variant_mapper = hgvs.variantmapper.VariantMapper(self.uta_conn)
# c. to n. projection for translation. Reference checking happens
# afterwards and has to see the allele the expression stated.
self._c_to_n_mapper = hgvs.variantmapper.VariantMapper(
self.uta_conn,
replace_reference=False,
prevalidation_level="INTRINSIC",

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.

I think prevalidation_level="INTRINSIC" turns off more than the ref check. In hgvs 1.5.x the extrinsic Validator is also where _c_within_cds_bound and _n_within_transcript_bounds live, so with this mapper a c. position past the CDS end (which should be written c.*N) is no longer rejected and maps into the 3′ UTR.

For example, on NM_006087.3 (CDS length 1335), c.1400dup or c.1400_1401insT (no stated ref, so the new check doesn't run either) used to raise HGVSInvalidVariantError ("Variant is outside CDS bounds") and would now produce an Allele. c.1400A>G would pass whenever the UTR base happens to be A.

Since the goal is to stop emitting Alleles from invalid HGVS, could we keep those bounds checks? For example: read the stated ref before projecting and keep using the default (validating) mapper, or call the extrinsic bounds checks explicitly. A test with an out-of-CDS c. position would lock this in.

)
self.data_proxy = data_proxy

def close(self) -> None:
Expand All @@ -49,6 +72,7 @@ def close(self) -> None:
"""
self.normalizer = None
self.variant_mapper = None
self._c_to_n_mapper = None
self.data_proxy = None
if self.uta_conn is not None:
self.uta_conn.close()
Expand Down Expand Up @@ -139,9 +163,19 @@ def get_position_and_state(self, sv: HgvsSequenceVariant) -> tuple[int, int, str

return start, end, state

def extract_allele_values(self, hgvs_expr: str) -> dict | None:
def extract_allele_values(
self, hgvs_expr: str, require_validation: bool = True
) -> dict | None:
"""Parse hgvs into a VRS Allele Object

:param hgvs_expr: HGVS expression to parse
:param require_validation: If `True`, a reference allele stated as
nucleotides (the `C` in `c.900C>A`, or `delC`) must match the
reference sequence, otherwise a `DataProxyValidationError` is
raised. A length (`del1`, `del1insAT`) is not a sequence and is not
compared. If `False`, a mismatch is only logged and the allele is
still returned. Defaults to `True`.

kwargs:
rle_seq_limit Optional(int): If RLE is set as the new state after
normalization, this sets the limit for the length of the `sequence`.
Expand Down Expand Up @@ -185,10 +219,27 @@ def extract_allele_values(self, hgvs_expr: str) -> dict | None:

# translate coding coordinates to positional coordinates, if necessary
if sv.type == "c":
sv = self.c_to_n(sv)
sv = self._project_c_to_n(sv)

(start, end, state) = self.get_position_and_state(sv)

# The HGVS expression may state the expected reference allele (e.g. the
# `C` in `c.900C>A`, or the deleted bases in `g.44908822delC`). A
# mismatch means the input itself is invalid: silently emitting a VRS
# Allele would produce a plausible-but-wrong variant object
# (ga4gh/vrs-python#364), so validate it against the reference
# sequence just like the gnomAD translator does. A length-only ref
# (`del1`) is not a sequence and is left alone.
ref_allele = _reference_bases(getattr(sv.posedit.edit, "ref", None))

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.

A stated ref using the ambiguity code N (e.g. NC_000019.10:g.44908822delN) gets compared literally against the reference and will always mismatch, so valid HGVS that doesn't name the bases is now rejected. Inputs like this appear in ClinVar-derived data. Could N (any position, or an all-N ref) be treated as a wildcard or skipped, with a test for delN / delNN?

if ref_allele:
self.data_proxy.validate_ref_seq(
sv.ac,
start,
end,
ref_allele.upper(),

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.

hgvs_re accepts r. expressions, whose stated refs are lowercase RNA with u. After .upper(), a u becomes U, which never equals the T in the reference sequence, so valid input like NM_xxx:r.100u>c or r.100_101delua will now raise DataProxyValidationError even when the ref is correct. Those inputs translated before this PR.

Mapping U→T before the comparison, or skipping the check for r. variants, would avoid the false rejection. A small test with a correct r. ref would be good to have.

require_validation=require_validation,
)

return {
"sequence_id": sv.ac,
"refget_accession": refget_accession,
Expand Down Expand Up @@ -331,6 +382,23 @@ def c_to_n(self, hgvs: HgvsSequenceVariant) -> HgvsSequenceVariant:
"""Perform hgvs library `c_to_n` method"""
return self.variant_mapper.c_to_n(hgvs)

def _project_c_to_n(self, sv: HgvsSequenceVariant) -> HgvsSequenceVariant:
"""Project a c. variant to n. coordinates, keeping its stated reference.

``VariantMapper.c_to_n`` validates that reference extrinsically and then
replaces it. A mismatch raises ``HGVSInvalidVariantError`` before
``require_validation`` applies, and a replacement makes the stated
allele compare equal to the sequence it was overwritten with. A
length-only deletion is rewritten too: the length lives in ``edit.ref``
while ``ref_s`` is unset, so ``fill_ref`` treats it as missing.
"""
stated_ref = getattr(sv.posedit.edit, "ref", None)
mapped = self._c_to_n_mapper.c_to_n(sv)
edit = mapped.posedit.edit
if hasattr(edit, "ref"):
edit.ref = stated_ref

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 simplification: rather than a second VariantMapper plus writing edit.ref = stated_ref back after fill_ref, the stated ref could be read from the parsed variant (sv.posedit.edit) before projecting, and the existing c_to_n used as-is. That avoids depending on hgvs internals (whether fill_ref mutates the edit, whether c_to_n copies it), keeps the bounds checks, and leaves one c.→n. path instead of two that behave differently (the public HgvsTools.c_to_n still uses the validating mapper).

return mapped


if __name__ == "__main__":
import os
Expand Down
31 changes: 31 additions & 0 deletions tests/data/hgvs_cache.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@
],
"value": "ATGAACTCAATGTTCAGGATT"
},
{
"func": "get_seq",
"args": [
"NM_006087.3",

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.

Minor: I don't think this get_seq(NM_006087.3, 1271, 1272) entry is read by the new code path. With replace_reference=False and INTRINSIC prevalidation, hgvs doesn't fetch the sequence for a sub, and the tests get reference bases from _CannedDataProxy. Dropping it, or noting why it's there, would avoid confusion about which source the check uses.

1271,
1272
],
"value": "G"
},
{
"func": "get_seq",
"args": [
Expand Down Expand Up @@ -1318,6 +1327,28 @@
}
}
},
{
"func": "get_tx_identity_info",
"args": [
"NM_006087.3"
],
"value": {
"psycopg2_dictrow": {
"tx_ac": "NM_006087.3",
"alt_ac": "NM_006087.3",
"alt_aln_method": "transcript",
"cds_start_i": 372,
"cds_end_i": 1707,
"lengths": [
429,
109,
111,
1903
],
"hgnc": "TUBB4A"
}
}
},
{
"func": "get_tx_identity_info",
"args": [
Expand Down
24 changes: 24 additions & 0 deletions tests/extras/cassettes/test_from_hgvs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,28 @@ interactions:
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/NC_000019.10?start=44908821&end=44908822
response:
body:
string: C
headers: {}
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/NC_012920.1?start=10082&end=10083
response:
body:
string: A
headers: {}
status:
code: 200
message: OK
version: 1
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,16 @@ interactions:
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/NC_000007.14?start=55181319&end=55181320
response:
body:
string: A
headers: {}
status:
code: 200
message: OK
version: 1
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,16 @@ interactions:
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/NM_001331029.1?start=871&end=872
response:
body:
string: A
headers: {}
status:
code: 200
message: OK
version: 1
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,16 @@ interactions:
status:
code: 200
message: OK
- request:
body: null
headers: {}
method: GET
uri: http://localhost:5000/seqrepo/1/sequence/NM_181798.1?start=1262&end=1263
response:
body:
string: G
headers: {}
status:
code: 200
message: OK
version: 1
Loading