From 17d66186959fd1c4c427f46610b3459443e3f93d Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:51:25 +0000 Subject: [PATCH] feat(annotator): read VRS Alleles back from annotated VCFs The VCF annotator writes enough INFO fields (with `--vrs-attributes`) to reconstruct the VRS Alleles of each record, but VRS-Python had no code to do so. Add `VcfReader`, whose `read()` method iterates over an annotated VCF and yields each pysam record together with its VRS Alleles: * The list of Alleles lines up with the `VRS_Allele_IDs` values: one per REF and ALT allele, or one per ALT allele for VCFs annotated with `--skip-ref` (INFO Number=A). Alleles without a VRS ID (`*` ALTs, untranslatable ALTs, records with a `VRS_Error`) are `None`. * Each Allele is built from the record's CHROM (resolved to a refget accession through the data proxy) and its VRS_Starts, VRS_Ends, VRS_States, VRS_Lengths and VRS_RepeatSubunitLengths values, as a LiteralSequenceExpression, ReferenceLengthExpression or LengthExpression state. Missing ("." or empty) values are mapped back the way the annotator wrote them: an empty sequence for LSEs and zero-length RLEs, no sequence for RLEs longer than the annotator's sequence limit. * Allele and location identifiers are computed the same way as by the translator, and the Allele ID must match the annotated one. * `VcfReaderError` is raised for VCFs without VRS attribute annotations and for records whose annotations are incomplete, invalid or don't reproduce the annotated ID. Tests round-trip the annotator's output (with and without REF alleles) against its NDJSON dump using the local test SeqRepo, and cover star alleles, failed records, each state type and malformed annotations. The VCF annotator docs describe the new reader. Closes #595 --- docs/extras/vcf_annotator.md | 23 +++ src/ga4gh/vrs/extras/annotator/vcf.py | 205 +++++++++++++++++++++++- tests/extras/test_vcf_reader.py | 221 ++++++++++++++++++++++++++ 3 files changed, 447 insertions(+), 2 deletions(-) create mode 100644 tests/extras/test_vcf_reader.py diff --git a/docs/extras/vcf_annotator.md b/docs/extras/vcf_annotator.md index eced28b0..3dfe28e3 100644 --- a/docs/extras/vcf_annotator.md +++ b/docs/extras/vcf_annotator.md @@ -50,3 +50,26 @@ vrs-annotate vcf --dataproxy-uri="seqrepo+http://mylabwebsite.org/seqrepo" --vcf `--help` >Show the options available + +## Reading VRS Alleles from an annotated VCF + +The [`VcfReader`](../../src/ga4gh/vrs/extras/annotator/vcf.py) class reconstructs the VRS Alleles from a VCF annotated with `--vrs-attributes` (or `vrs_attributes=True` in `VcfAnnotator.annotate()`). It iterates over the VCF's records and yields each pysam record together with a list of VRS Alleles: + +```python +from pathlib import Path + +from ga4gh.vrs.dataproxy import create_dataproxy +from ga4gh.vrs.extras.annotator.vcf import VcfReader + +data_proxy = create_dataproxy("seqrepo+http://localhost:5000/seqrepo") +reader = VcfReader(data_proxy) +for record, vrs_alleles in reader.read(Path("out.vcf.gz"), assembly="GRCh38"): + for vrs_allele in vrs_alleles: + if vrs_allele is not None: + print(record.chrom, record.pos, vrs_allele.id) +``` + +* The list of VRS Alleles has one value per REF and ALT allele (`record.alleles`), or per ALT allele (`record.alts`) if the VCF was annotated with `--skip-ref`. It holds `None` for alleles without a VRS ID, such as `*` ALTs, and for every allele of a record that failed annotation (see its `VRS_Error` INFO field). +* The data proxy is only used to look up the refget accession for each `CHROM`, and `assembly` must be the assembly used to annotate the VCF. +* The identifier of each reconstructed VRS Allele is checked against its `VRS_Allele_IDs` annotation. A `VcfReaderError` is raised if they differ, if the annotations of a record are incomplete, or if the VCF wasn't annotated with VRS attributes. +* `ReferenceLengthExpression` sequences longer than 50 residues aren't written to the annotated VCF, so these states are read without a `sequence`. This doesn't change their VRS identifiers. diff --git a/src/ga4gh/vrs/extras/annotator/vcf.py b/src/ga4gh/vrs/extras/annotator/vcf.py index 7d1a3593..ed84e3c6 100644 --- a/src/ga4gh/vrs/extras/annotator/vcf.py +++ b/src/ga4gh/vrs/extras/annotator/vcf.py @@ -1,14 +1,19 @@ -"""Annotate VCFs with VRS identifiers and attributes.""" +"""Annotate VCFs with VRS identifiers and attributes, and read VRS Alleles back from +annotated VCFs. +""" import abc import logging import pickle +from collections.abc import Iterator from enum import Enum from pathlib import Path from typing import Literal import pysam +from pydantic import ValidationError +from ga4gh.core import ga4gh_identify from ga4gh.core.identifiers import ( VrsObjectIdentifierIs, use_ga4gh_compute_identifier_when, @@ -16,7 +21,15 @@ from ga4gh.vrs import VRS_VERSION, VrsType, __version__ from ga4gh.vrs.dataproxy import _DataProxy from ga4gh.vrs.extras.translator import AlleleTranslator -from ga4gh.vrs.models import Allele, Range +from ga4gh.vrs.models import ( + Allele, + LengthExpression, + LiteralSequenceExpression, + Range, + ReferenceLengthExpression, + SequenceLocation, + SequenceReference, +) _logger = logging.getLogger(__name__) @@ -41,6 +54,10 @@ class VcfAnnotatorAbortError(VcfAnnotatorError): """ +class VcfReaderError(Exception): + """Raise for VCFs that VRS Alleles can't be read back from""" + + class FieldName(str, Enum): """Define VCF field names for VRS annotations""" @@ -65,6 +82,17 @@ class FieldName(str, Enum): ) +# INFO fields, in addition to ``FieldName.IDS_FIELD``, that ``VcfAnnotator`` adds when +# run with VRS attributes. ``VcfReader`` needs all of them to reconstruct VRS Alleles. +_VRS_ATTRIBUTE_FIELDS = ( + FieldName.STARTS_FIELD, + FieldName.ENDS_FIELD, + FieldName.STATES_FIELD, + FieldName.LENGTHS_FIELD, + FieldName.REPEAT_SUBUNIT_LENGTHS_FIELD, +) + + # VCF character escape map VCF_ESCAPE_MAP = str.maketrans( { @@ -662,3 +690,176 @@ def on_vrs_object_collection( output_ndjson_path = kwargs.get(self.ndjson_arg_name) if output_ndjson_path is not None: dump_alleles_to_ndjson(vrs_alleles_collection, output_ndjson_path) + + +class VcfReader: + """Read VRS Alleles back from a VCF annotated with VRS attributes. + + The input VCF must have been annotated with VRS attributes (e.g. by + ``VcfAnnotator.annotate()`` with ``vrs_attributes=True``, or by + ``vrs-annotate vcf --vrs-attributes``). Each VRS Allele is reconstructed from the + record's CHROM and its VRS INFO fields, and its computed identifier must match the + annotated ``VRS_Allele_IDs`` value. + """ + + def __init__(self, data_proxy: _DataProxy) -> None: + """Initialize the VcfReader class. + + :param data_proxy: GA4GH sequence dataproxy instance, used to look up the + refget accession for each CHROM + """ + self.data_proxy = data_proxy + + def read( + self, input_vcf_path: Path | Literal["-"], assembly: str = "GRCh38" + ) -> Iterator[tuple[pysam.VariantRecord, list[Allele | None]]]: + """Iterate over the records of an annotated VCF along with their VRS Alleles. + + For each record, yield the pysam record and a list of identified VRS Alleles, + one per ``VRS_Allele_IDs`` value: one per REF and ALT allele + (``record.alleles``) if the VCF was annotated with REF alleles, or one per ALT + allele (``record.alts``) if not. The list holds + ``None`` for alleles without a VRS ID, such as ``*`` ALTs, and for every + allele of a record that failed annotation (see its ``VRS_Error`` INFO field). + + The input VCF is opened when iteration starts and closed when iteration ends. + + ReferenceLengthExpression sequences longer than the annotator's sequence + limit aren't stored in the VCF, so these states are returned without a + ``sequence``. This doesn't change their VRS identifiers. + + :param input_vcf_path: Location of input VCF (or "-" to read from stdin) + :param assembly: The assembly used in `input_vcf_path` data + :raise VcfReaderError: if the VCF wasn't annotated with VRS attributes, or if + the VRS Alleles of a record can't be reconstructed from its annotations, + including when a computed identifier doesn't match the annotated one + """ + pysam_in_filename = ( + "-" if input_vcf_path == "-" else str(input_vcf_path.absolute()) + ) + with pysam.VariantFile(filename=pysam_in_filename, mode="r") as vcf: + missing_fields = [ + field.value + for field in (FieldName.IDS_FIELD, *_VRS_ATTRIBUTE_FIELDS) + if field.value not in vcf.header.info + ] + if missing_fields: + msg = f"VCF is missing VRS annotation INFO fields {', '.join(missing_fields)} -- it must be annotated with VRS attributes (`--vrs-attributes`) to read VRS Alleles from it." + raise VcfReaderError(msg) + includes_ref = vcf.header.info[FieldName.IDS_FIELD.value].number == "R" + + for record in vcf: + yield record, self._get_vrs_alleles(record, assembly, includes_ref) + + def _get_vrs_alleles( + self, record: pysam.VariantRecord, assembly: str, includes_ref: bool + ) -> list[Allele | None]: + """Reconstruct the VRS Alleles for a record from its VRS annotations. + + :param record: A row in the VCF file + :param assembly: The assembly used in `record` + :param includes_ref: Whether the VCF was annotated with VRS Alleles for REFs + :return: VRS Alleles, or ``None`` for alleles without a VRS ID, in the order of + ``record.alleles`` if `includes_ref`, otherwise of ``record.alts`` + :raise VcfReaderError: if the VRS annotations of `record` are incomplete or + inconsistent + """ + num_alleles = len(record.alleles) if includes_ref else len(record.alts or ()) + if FieldName.IDS_FIELD.value not in record.info: + return [None] * num_alleles + + vcf_coords = f"{record.chrom}-{record.pos}" + ids, starts, ends, states, lengths, repeat_subunit_lengths = ( + self._get_info_values(record, field, num_alleles, vcf_coords) + for field in (FieldName.IDS_FIELD, *_VRS_ATTRIBUTE_FIELDS) + ) + refget_accession = None + vrs_alleles = [] + for vrs_id, start, end, sequence, length, repeat_subunit_length in zip( + ids, starts, ends, states, lengths, repeat_subunit_lengths, strict=True + ): + if vrs_id is None: + vrs_alleles.append(None) + continue + + if start is None or end is None: + msg = f"VRS Allele {vrs_id} at {vcf_coords} is missing its {FieldName.STARTS_FIELD.value} or {FieldName.ENDS_FIELD.value} value" + raise VcfReaderError(msg) + + if refget_accession is None: + sequence_id = f"{assembly}:{record.chrom}" + refget_accession = self.data_proxy.derive_refget_accession(sequence_id) + if refget_accession is None: + msg = f"Unable to find refget accession for {sequence_id}" + raise VcfReaderError(msg) + + try: + vrs_allele = Allele( + location=SequenceLocation( + sequenceReference=SequenceReference( + refgetAccession=refget_accession + ), + start=start, + end=end, + ), + state=self._get_state(sequence, length, repeat_subunit_length), + ) + except ValidationError as e: + msg = f"Invalid VRS annotations for VRS Allele {vrs_id} at {vcf_coords}: {e}" + raise VcfReaderError(msg) from e + vrs_allele.id = ga4gh_identify(vrs_allele) + vrs_allele.location.id = ga4gh_identify(vrs_allele.location) + if vrs_allele.id != vrs_id: + msg = f"VRS Allele reconstructed at {vcf_coords} has ID {vrs_allele.id}, but was annotated with {vrs_id}" + raise VcfReaderError(msg) + vrs_alleles.append(vrs_allele) + return vrs_alleles + + @staticmethod + def _get_info_values( + record: pysam.VariantRecord, field: FieldName, num_alleles: int, vcf_coords: str + ) -> tuple: + """Get the per-allele values of a VRS INFO field, with missing values as + ``None``. + + :param record: A row in the VCF file + :param field: VRS INFO field to get + :param num_alleles: Number of values the field must have + :param vcf_coords: CHR-POS of `record`, for error messages + :return: The values of `field`, or ``None`` for each allele if `record` doesn't + have it + :raise VcfReaderError: if `field` doesn't have `num_alleles` values + """ + values = record.info.get(field.value) + if values is None: + return (None,) * num_alleles + if len(values) != num_alleles: + msg = f"Expected {num_alleles} {field.value} values at {vcf_coords}, but found {len(values)}" + raise VcfReaderError(msg) + # Missing String values are written as "." (or "" by older VRS-Python versions) + return tuple(None if value in ("", ".") else value for value in values) + + @staticmethod + def _get_state( + sequence: str | None, length: int | None, repeat_subunit_length: int | None + ) -> LiteralSequenceExpression | ReferenceLengthExpression | LengthExpression: + """Construct a VRS Allele state from its VRS annotation values. + + :param sequence: ``VRS_States`` value + :param length: ``VRS_Lengths`` value + :param repeat_subunit_length: ``VRS_RepeatSubunitLengths`` value + :return: LiteralSequenceExpression if there's no `length`, otherwise + ReferenceLengthExpression if there's a `repeat_subunit_length`, otherwise + LengthExpression + """ + # An empty sequence is written as a missing value, which is also used for + # ReferenceLengthExpression sequences left out because of their length. + if length is None: + return LiteralSequenceExpression(sequence=sequence or "") + if repeat_subunit_length is None: + return LengthExpression(length=length) + if sequence is None and length == 0: + sequence = "" + return ReferenceLengthExpression( + length=length, repeatSubunitLength=repeat_subunit_length, sequence=sequence + ) diff --git a/tests/extras/test_vcf_reader.py b/tests/extras/test_vcf_reader.py new file mode 100644 index 00000000..ea85dda3 --- /dev/null +++ b/tests/extras/test_vcf_reader.py @@ -0,0 +1,221 @@ +"""Ensure proper functionality of VcfReader""" + +import json +from pathlib import Path + +import pytest + +from ga4gh.vrs.dataproxy import SeqRepoDataProxy +from ga4gh.vrs.extras.annotator.vcf import VcfAnnotator, VcfReader, VcfReaderError + +TEST_DATA_DIR = Path("tests/extras/data") + + +@pytest.fixture +def vcf_reader(dataproxy: SeqRepoDataProxy): + return VcfReader(dataproxy) + + +@pytest.mark.parametrize("compute_for_ref", [True, False]) +def test_read_vcf_round_trip( + dataproxy: SeqRepoDataProxy, + vcf_reader: VcfReader, + tmp_path: Path, + compute_for_ref: bool, +): + """Test that the VRS Alleles read from an annotated VCF are the ones the annotator + created + """ + output_vcf = tmp_path / "test_vcf_output.vcf.gz" + output_ndjson = tmp_path / "test_vcf_output.ndjson" + VcfAnnotator(dataproxy).annotate( + TEST_DATA_DIR / "test_vcf_input.vcf", + output_vcf, + vrs_attributes=True, + compute_for_ref=compute_for_ref, + output_ndjson_path=output_ndjson, + ) + with output_ndjson.open() as f: + expected_alleles = [json.loads(line) for line in f] + + read_alleles = [] + for record, vrs_alleles in vcf_reader.read(output_vcf): + expected_num_alleles = ( + len(record.alleles) if compute_for_ref else len(record.alts) + ) + assert len(vrs_alleles) == expected_num_alleles + read_alleles += [ + vrs_allele.model_dump(exclude_none=True) + for vrs_allele in vrs_alleles + if vrs_allele is not None + ] + assert read_alleles == expected_alleles + + +def test_read_vcf(vcf_reader: VcfReader): + """Test the VRS Alleles read for each kind of annotated record""" + records = list(vcf_reader.read(TEST_DATA_DIR / "test_vcf_expected_output.vcf")) + assert len(records) == 8 + vrs_alleles_by_pos = {record.pos: vrs_alleles for record, vrs_alleles in records} + + # REF is a ReferenceLengthExpression, ALT is a LiteralSequenceExpression + ref, alt = vrs_alleles_by_pos[82664] + assert ref.id == "ga4gh:VA.esmv8nARRRdSysDFuIErJxRAdUSVsWNE" + assert ref.location.id == "ga4gh:SL.sXl66xA1nei_abGw9YmGkiAS-C9l3nUH" + assert ( + ref.location.sequenceReference.refgetAccession + == "SQ.IIB53T8CNeJJdUqzn9V_JnRtQadwWCbl" + ) + assert ref.location.start == 82663 + assert ref.location.end == 82664 + assert ref.state.model_dump(exclude_none=True) == { + "type": "ReferenceLengthExpression", + "length": 1, + "sequence": "C", + "repeatSubunitLength": 1, + } + assert alt.id == "ga4gh:VA.b9AIUegs1SOYO7nKY8l01yllkyUns-u4" + assert alt.state.model_dump(exclude_none=True) == { + "type": "LiteralSequenceExpression", + "sequence": "T", + } + + # Deletion whose empty ALT sequence is annotated as a missing VRS_States value + _, alt = vrs_alleles_by_pos[490414] + assert alt.id == "ga4gh:VA.lok7a3lot_cvUyw626otpJi4yxk0X07v" + assert alt.state.model_dump(exclude_none=True) == { + "type": "ReferenceLengthExpression", + "length": 0, + "sequence": "", + "repeatSubunitLength": 2, + } + + # Star allele + ref, star, alt = vrs_alleles_by_pos[54220024] + assert ref.id == "ga4gh:VA.LlmfhAC3gQlVQUwXWYiYjrn5V_K8vBz1" + assert star is None + assert alt.id == "ga4gh:VA.I7J3i1B36BACEUINcTwEh7uMv3I-PXT1" + + # Record that failed annotation + assert vrs_alleles_by_pos[54220999] == [None, None] + + # ALT that couldn't be translated + ref, alt, invalid_alt = vrs_alleles_by_pos[54221654] + assert ref.id == "ga4gh:VA.kea5G-J1teg0iHMbgUELy-4L9lbJkgoj" + assert alt.id == "ga4gh:VA.Zzlc24htmBV1HZZzWYgPD2_GfMInkrZu" + assert invalid_alt is None + + +def test_read_vcf_altsonly(vcf_reader: VcfReader): + """Test that VRS Alleles of a VCF annotated without REFs match its ALTs""" + vrs_alleles_by_pos = { + record.pos: vrs_alleles + for record, vrs_alleles in vcf_reader.read( + TEST_DATA_DIR / "test_vcf_expected_altsonly_output.vcf" + ) + } + (alt,) = vrs_alleles_by_pos[82664] + assert alt.id == "ga4gh:VA.b9AIUegs1SOYO7nKY8l01yllkyUns-u4" + star, alt = vrs_alleles_by_pos[54220024] + assert star is None + assert alt.id == "ga4gh:VA.I7J3i1B36BACEUINcTwEh7uMv3I-PXT1" + assert vrs_alleles_by_pos[54220999] == [None] + + +@pytest.mark.parametrize( + "input_vcf", + ["test_vcf_input.vcf", "test_vcf_expected_output_no_vrs_attrs.vcf"], +) +def test_read_vcf_not_annotated(vcf_reader: VcfReader, input_vcf: str): + """Test that a VCF without VRS attribute annotations is rejected""" + with pytest.raises(VcfReaderError, match="missing VRS annotation INFO fields"): + next(vcf_reader.read(TEST_DATA_DIR / input_vcf)) + + +@pytest.mark.parametrize( + ("annotation", "tampered_annotation", "error_match"), + [ + ( + "VRS_Starts=82663,82663", + "VRS_Starts=82662,82663", + r"VRS Allele reconstructed at chr19-82664 has ID ga4gh:VA\.\S+, but was annotated with ga4gh:VA\.esmv8nARRRdSysDFuIErJxRAdUSVsWNE", + ), + ( + "VRS_Ends=82664,82664", + "VRS_Ends=.,82664", + "VRS Allele ga4gh:VA.esmv8nARRRdSysDFuIErJxRAdUSVsWNE at chr19-82664 is missing its VRS_Starts or VRS_Ends value", + ), + ( + "VRS_States=C,T", + "VRS_States=C,t", + "Invalid VRS annotations for VRS Allele ga4gh:VA.b9AIUegs1SOYO7nKY8l01yllkyUns-u4 at chr19-82664", + ), + ( + "VRS_Lengths=1,.", + "VRS_Lengths=1", + "Expected 2 VRS_Lengths values at chr19-82664, but found 1", + ), + ], +) +def test_read_vcf_invalid_annotations( + vcf_reader: VcfReader, + tmp_path: Path, + annotation: str, + tampered_annotation: str, + error_match: str, +): + """Test that a record whose VRS Alleles can't be reconstructed is rejected""" + vcf_text = (TEST_DATA_DIR / "test_vcf_expected_output.vcf").read_text() + assert annotation in vcf_text + input_vcf = tmp_path / "test_vcf_tampered.vcf" + input_vcf.write_text(vcf_text.replace(annotation, tampered_annotation, 1)) + + with pytest.raises(VcfReaderError, match=error_match): + list(vcf_reader.read(input_vcf)) + + +@pytest.mark.parametrize( + ("sequence", "length", "repeat_subunit_length", "expected"), + [ + ("T", None, None, {"type": "LiteralSequenceExpression", "sequence": "T"}), + (None, None, None, {"type": "LiteralSequenceExpression", "sequence": ""}), + ( + "CTTTCTTT", + 8, + 4, + { + "type": "ReferenceLengthExpression", + "length": 8, + "sequence": "CTTTCTTT", + "repeatSubunitLength": 4, + }, + ), + ( + None, + 0, + 2, + { + "type": "ReferenceLengthExpression", + "length": 0, + "sequence": "", + "repeatSubunitLength": 2, + }, + ), + # sequence left out of the annotations because it's longer than RLE_SEQ_LIMIT + ( + None, + 60, + 1, + { + "type": "ReferenceLengthExpression", + "length": 60, + "repeatSubunitLength": 1, + }, + ), + (None, 15, None, {"type": "LengthExpression", "length": 15}), + ], +) +def test_get_state(sequence, length, repeat_subunit_length, expected): + """Test that each kind of annotated state is reconstructed""" + state = VcfReader._get_state(sequence, length, repeat_subunit_length) + assert state.model_dump(exclude_none=True) == expected