diff --git a/src/ga4gh/vrs/extras/translator.py b/src/ga4gh/vrs/extras/translator.py index 90c01d6c..36064651 100644 --- a/src/ga4gh/vrs/extras/translator.py +++ b/src/ga4gh/vrs/extras/translator.py @@ -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 diff --git a/src/ga4gh/vrs/utils/hgvs_tools.py b/src/ga4gh/vrs/utils/hgvs_tools.py index be773a90..94271965 100644 --- a/src/ga4gh/vrs/utils/hgvs_tools.py +++ b/src/ga4gh/vrs/utils/hgvs_tools.py @@ -17,6 +17,22 @@ _logger = logging.getLogger(__name__) +def _reference_bases(ref: object) -> str | None: + """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. @@ -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", + ) self.data_proxy = data_proxy def close(self) -> None: @@ -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() @@ -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`. @@ -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)) + if ref_allele: + self.data_proxy.validate_ref_seq( + sv.ac, + start, + end, + ref_allele.upper(), + require_validation=require_validation, + ) + return { "sequence_id": sv.ac, "refget_accession": refget_accession, @@ -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 + return mapped + if __name__ == "__main__": import os diff --git a/tests/data/hgvs_cache.json b/tests/data/hgvs_cache.json index f26aea13..087ee232 100644 --- a/tests/data/hgvs_cache.json +++ b/tests/data/hgvs_cache.json @@ -224,6 +224,15 @@ ], "value": "ATGAACTCAATGTTCAGGATT" }, + { + "func": "get_seq", + "args": [ + "NM_006087.3", + 1271, + 1272 + ], + "value": "G" + }, { "func": "get_seq", "args": [ @@ -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": [ diff --git a/tests/extras/cassettes/test_from_hgvs.yaml b/tests/extras/cassettes/test_from_hgvs.yaml index ed06582a..15da4b72 100644 --- a/tests/extras/cassettes/test_from_hgvs.yaml +++ b/tests/extras/cassettes/test_from_hgvs.yaml @@ -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 diff --git a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml index 22b2d38f..1a2705bf 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml @@ -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 diff --git a/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml b/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml index d86ad12f..0e213e79 100644 --- a/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml +++ b/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml @@ -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 diff --git a/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml b/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml index 34775aab..2b4c4a3a 100644 --- a/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml +++ b/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml @@ -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 diff --git a/tests/extras/test_allele_translator.py b/tests/extras/test_allele_translator.py index a010ec09..de6def10 100644 --- a/tests/extras/test_allele_translator.py +++ b/tests/extras/test_allele_translator.py @@ -1,8 +1,10 @@ +from typing import ClassVar + import pytest from pydantic import ValidationError from ga4gh.vrs import models -from ga4gh.vrs.dataproxy import DataProxyValidationError +from ga4gh.vrs.dataproxy import DataProxyValidationError, _DataProxy from ga4gh.vrs.extras.translator import AlleleTranslator @@ -1066,3 +1068,184 @@ def test_from_vrs_non_variation_type(case): with pytest.raises(ValidationError) as e: tlr.translate_from({"type": case["type"]}, fmt="vrs") assert e.value.errors()[0]["type"] == "union_tag_invalid" + + +# --------------------------------------------------------------------------- +# Regression tests for https://github.com/ga4gh/vrs-python/issues/364 +# ("hgvs to vrs is returning valid results when hgvs has IncorrectReferenceAllele") +# +# Sequence comparisons use canned ground truth. Coding-coordinate mapping goes +# through the real VariantMapper.c_to_n and the recorded UTA cache +# (tests/data/hgvs_cache.json), including NM_006087.3. The default mapper +# rejects that transcript's c.900C>A with HGVSInvalidVariantError; these tests +# require DataProxyValidationError instead, and require_validation=False must +# still return the allele. + + +class _CannedDataProxy(_DataProxy): + """Minimal data proxy backed by canned ground-truth reference sequences. + + Only the sequence/metadata lookups are faked; reference validation uses + the real `_DataProxy.validate_ref_seq` logic. + """ + + # (accession, interbase start, interbase end) -> true reference sequence + TRUTH: ClassVar[dict] = { + # NM_006087.3 (TUBB4A): CDS is 373..1707, so c.900 == n.1272. The true + # base there is G, as reported by the ClinGen Allele Registry for the + # NM_006087.3:c.900C>A expression in issue #364 (IncorrectReferenceAllele: + # "given=C, found=G"), independently confirmed against NCBI RefSeq. + ("NM_006087.3", 1271, 1272): "G", + # NM_001331029.1 c.722 is n.872. Recorded UTA sequence at that base is A. + ("NM_001331029.1", 871, 872): "A", + # GRCh38 chr19:44908822, true ref C (matches the C>T test expression) + ("NC_000019.10", 44908821, 44908822): "C", + } + + def get_sequence( + self, identifier: str, start: int | None = None, end: int | None = None + ) -> str: + return self.TRUTH[(identifier, start, end)] + + def get_metadata(self, _identifier: str) -> dict: + # Longer than any coordinate these tests use, including GRCh38 chr19. + return {"aliases": ["ga4gh:SQ." + "A" * 32], "length": 10**9} + + +@pytest.fixture +def tlr_canned(): + """AlleleTranslator backed by canned reference data. + + UTA lookups are the shared recorded provider from conftest, so c. to n. + mapping is the real VariantMapper rather than a coordinate stub. + """ + return AlleleTranslator(data_proxy=_CannedDataProxy(), identify=False) + + +def test_from_hgvs_wrong_ref_allele_raises(tlr_canned): + """A mismatched reference allele in the HGVS expression must raise, not + silently produce a plausible-but-wrong VRS Allele (issue #364). + + Mapping uses the real VariantMapper. The default mapper raises + HGVSInvalidVariantError for this expression before require_validation + can turn the mismatch into DataProxyValidationError. + """ + error_msg = ( + "Reference mismatch at NM_006087.3 position 1271-1272 " + "(input gave 'C' but correct ref is 'G')" + ) + + with pytest.raises(DataProxyValidationError) as e: + tlr_canned._from_hgvs("NM_006087.3:c.900C>A", do_normalize=False) + assert str(e.value) == error_msg + + with pytest.raises(DataProxyValidationError) as e: + tlr_canned.translate_from( + "NM_006087.3:c.900C>A", fmt="hgvs", do_normalize=False + ) + assert str(e.value) == error_msg + + +def test_from_hgvs_wrong_ref_allele_no_validation(tlr_canned, caplog): + """require_validation=False keeps the legacy behavior: the allele is + returned and the mismatch is only logged. + + This has to survive the real VariantMapper.c_to_n, which otherwise raises + HGVSInvalidVariantError for NM_006087.3:c.900C>A. + """ + with caplog.at_level("WARNING"): + allele = tlr_canned._from_hgvs( + "NM_006087.3:c.900C>A", do_normalize=False, require_validation=False + ) + assert (allele.location.start, allele.location.end) == (1271, 1272) + assert allele.state.sequence.root == "A" + assert "input gave 'C' but correct ref is 'G'" in caplog.text + + +def test_from_hgvs_wrong_ref_on_recorded_transcript(tlr_canned, caplog): + """Same contract on a transcript already in the recorded UTA cache. + + NM_001331029.1:c.722 is n.872 and the recorded reference base is A, so + c.722C>G is a reference mismatch. require_validation=False still returns it. + """ + error_msg = ( + "Reference mismatch at NM_001331029.1 position 871-872 " + "(input gave 'C' but correct ref is 'A')" + ) + with pytest.raises(DataProxyValidationError) as e: + tlr_canned._from_hgvs("NM_001331029.1:c.722C>G", do_normalize=False) + assert str(e.value) == error_msg + + with caplog.at_level("WARNING"): + allele = tlr_canned._from_hgvs( + "NM_001331029.1:c.722C>G", + do_normalize=False, + require_validation=False, + ) + assert (allele.location.start, allele.location.end) == (871, 872) + assert allele.state.sequence.root == "G" + assert "input gave 'C' but correct ref is 'A'" in caplog.text + + +def test_from_hgvs_correct_ref_allele_passes(tlr_canned): + """HGVS expressions whose stated ref matches the reference sequence still + translate cleanly (substitution and deletion-with-ref forms). + """ + allele = tlr_canned.translate_from( + "NM_006087.3:c.900G>A", fmt="hgvs", do_normalize=False + ) + assert (allele.location.start, allele.location.end) == (1271, 1272) + assert allele.state.sequence.root == "A" + + allele = tlr_canned.translate_from( + "NC_000019.10:g.44908822C>T", fmt="hgvs", do_normalize=False + ) + assert (allele.location.start, allele.location.end) == (44908821, 44908822) + assert allele.state.sequence.root == "T" + + allele = tlr_canned.translate_from( + "NC_000019.10:g.44908822delC", fmt="hgvs", do_normalize=False + ) + assert (allele.location.start, allele.location.end) == (44908821, 44908822) + assert allele.state.sequence.root == "" + + +def test_from_hgvs_wrong_ref_allele_del_raises(tlr_canned): + """The deletion-with-ref form is validated too.""" + with pytest.raises(DataProxyValidationError) as e: + tlr_canned.translate_from( + "NC_000019.10:g.44908822delG", fmt="hgvs", do_normalize=False + ) + assert "correct ref is 'C'" in str(e.value) + + +def test_from_hgvs_length_only_ref_skips_comparison(tlr_canned): + """A length in edit.ref is not a sequence, so del1 and del1ins are not + compared with the reference base. + + The true base at NC_000019.10:g.44908822 is C. Comparing the stored ref + ``1`` with that base would reject a deletion that states no bases. + """ + allele = tlr_canned.translate_from( + "NC_000019.10:g.44908822del1", fmt="hgvs", do_normalize=False + ) + assert (allele.location.start, allele.location.end) == (44908821, 44908822) + assert allele.state.sequence.root == "" + + allele = tlr_canned.translate_from( + "NC_000019.10:g.44908822del1insAT", fmt="hgvs", do_normalize=False + ) + assert (allele.location.start, allele.location.end) == (44908821, 44908822) + assert allele.state.sequence.root == "AT" + + +def test_from_hgvs_no_ref_allele_skips_validation(tlr_canned): + """Edits that state no reference allele (ins/dup/bare del) skip validation + entirely -- the canned proxy raises KeyError on any sequence lookup, so + this fails if validation is attempted. + """ + allele = tlr_canned.translate_from( + "NC_000019.10:g.44908822_44908823insT", fmt="hgvs", do_normalize=False + ) + assert (allele.location.start, allele.location.end) == (44908822, 44908822) + assert allele.state.sequence.root == "T"