From 8851679e2f8a38a1cd2e95fbd0c7dfa52ac2185a Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:36:00 +0530 Subject: [PATCH] feat(annotator): add --rle-seq-limit option to vrs-annotate vcf The maximum length of the optional ReferenceLengthExpression sequence could only be changed for the VCF annotator through the GA4GH_VRS_RLE_SEQ_LIMIT environment variable, which applies to the whole process. There was no way to set it for a single annotation run, either from the CLI or when constructing a VcfAnnotator. - Add an `rle_seq_limit` argument to `AbstractVcfAnnotator.__init__()`, defaulting to the configured `RLE_SEQ_LIMIT`. It is passed to the translator for every allele, so it controls the sequence in the VRS objects that are collected (PKL/NDJSON output, `on_vrs_object()`), and it replaces the module-level limit used for the VRS_States INFO field. - Add a `--rle-seq-limit` option to `vrs-annotate vcf`. Like the environment variable, it takes a non-negative integer, 0 to omit the sequence, or `none` (case-insensitive) for no limit. Invalid values are rejected with a usage error. When the option is not given, the configured default is used. - Document the option and the constructor argument in the VCF annotator docs. VRS IDs are unaffected, since the RLE sequence is not part of the digest. Tests reuse the test_annotate_vcf_rle cassette: the constructor argument overrides the configured default (in both directions) for VRS_States and NDJSON output, and the CLI option overrides the configured default, falls back to it when omitted, and rejects invalid values. The configured_modules fixture now also reloads the CLI module, so its option default follows the configured environment. Closes #347 --- docs/extras/vcf_annotator.md | 27 +++++- src/ga4gh/vrs/extras/annotator/cli.py | 36 ++++++- src/ga4gh/vrs/extras/annotator/vcf.py | 15 ++- tests/extras/conftest.py | 1 + tests/extras/test_annotate_vcf.py | 133 ++++++++++++++++++++++++++ 5 files changed, 205 insertions(+), 7 deletions(-) diff --git a/docs/extras/vcf_annotator.md b/docs/extras/vcf_annotator.md index 8187a526..bba3c744 100644 --- a/docs/extras/vcf_annotator.md +++ b/docs/extras/vcf_annotator.md @@ -43,10 +43,10 @@ The default is `50` bases. Use a non-negative integer, `0` to omit the optional sequence, or `none` (case-insensitive) for no limit. Invalid values raise a `ValueError` when VRS-Python is imported. -The normalizer, translator, and VCF writer share this setting. Explicit -`rle_seq_limit` arguments to normalization or translation override the default; -the VCF writer still applies the configured output limit. Required -`LiteralSequenceExpression.sequence` values are unaffected. +The normalizer, translator, and VCF annotator share this setting. Explicit +`rle_seq_limit` arguments to normalization, translation, or the `VcfAnnotator` +constructor override the default. Required `LiteralSequenceExpression.sequence` +values are unaffected. For example: @@ -54,10 +54,29 @@ For example: GA4GH_VRS_RLE_SEQ_LIMIT=100 vrs-annotate vcf --vrs-attributes --vcf-out=out.vcf input.vcf ``` +To set the limit for a single `vrs-annotate` run, use the `--rle-seq-limit` +option, which takes priority over the environment variable and accepts the same +values. The limit applies to the `VRS_States` INFO field and to the VRS objects +written with `--pkl-out` or `--ndjson-out`. VRS IDs do not depend on it, because +the optional sequence is not part of the computed digest: + +```shell +vrs-annotate vcf --rle-seq-limit=none --vrs-attributes --vcf-out=out.vcf input.vcf +``` + +In Python, pass `rle_seq_limit` when creating the annotator: + +```python +annotator = VcfAnnotator(data_proxy, rle_seq_limit=None) # no limit +``` + ### Other Options `--vrs-attributes` >Will include VRS_Start, VRS_End, VRS_State fields in the INFO field. +`--rle-seq-limit` [INTEGER-OR-NONE] +>Maximum length of the optional sequence in ReferenceLengthExpression states. Use 0 to omit the sequence, or `none` for no limit. [default: `GA4GH_VRS_RLE_SEQ_LIMIT`, or 50] + `--assembly` [TEXT] >The assembly that the `vcf-in` data uses. [default: GRCh38] diff --git a/src/ga4gh/vrs/extras/annotator/cli.py b/src/ga4gh/vrs/extras/annotator/cli.py index 4ebdb206..4804fe27 100644 --- a/src/ga4gh/vrs/extras/annotator/cli.py +++ b/src/ga4gh/vrs/extras/annotator/cli.py @@ -12,6 +12,7 @@ import click +from ga4gh.vrs.config import RLE_SEQ_LIMIT from ga4gh.vrs.dataproxy import create_dataproxy from ga4gh.vrs.extras.annotator.vcf import VcfAnnotator, VcfAnnotatorArgsError @@ -89,6 +90,27 @@ def convert( return self._inner.convert(value, param, ctx) +class RleSeqLimit(click.ParamType): + """click ParamType for RLE sequence limits: a non-negative integer or 'none'""" + + name = "integer-or-none" + + def convert( + self, value: str | int, param: click.Parameter | None, ctx: click.Context | None + ) -> int | None: + """Convert the value to a non-negative integer, or ``None`` for 'none'""" + if isinstance(value, str) and value.lower() == "none": + return None + msg = f"{value!r} is not a non-negative integer or 'none'." + try: + limit = int(value) + except ValueError: + self.fail(msg, param, ctx) + if limit < 0: + self.fail(msg, param, ctx) + return limit + + @_cli.command(name="vcf") @_log_level_option @click.argument( @@ -132,6 +154,17 @@ def convert( default=False, help="Include VRS_Start, VRS_End, and VRS_State fields in the VCF output INFO field.", ) +@click.option( + "--rle-seq-limit", + type=RleSeqLimit(), + default=RLE_SEQ_LIMIT, + help=( + "Maximum length of the optional sequence in ReferenceLengthExpression states, " + "applied to VRS objects and the VRS_States INFO field. Use 0 to omit the " + "sequence, or 'none' for no limit. Defaults to the GA4GH_VRS_RLE_SEQ_LIMIT " + "environment variable, or 50 if it is not set." + ), +) @click.option( "--dataproxy-uri", required=False, @@ -171,6 +204,7 @@ def _annotate_vcf_cli( pkl_out: Path | None, ndjson_out: Path | None, vrs_attributes: bool, + rle_seq_limit: int | None, dataproxy_uri: str, assembly: str, skip_ref: bool, @@ -199,7 +233,7 @@ def _annotate_vcf_cli( * seqrepo+:../relative/path/to/seqrepo/root """ # noqa: D301 data_proxy = create_dataproxy(dataproxy_uri) - annotator = VcfAnnotator(data_proxy) + annotator = VcfAnnotator(data_proxy, rle_seq_limit=rle_seq_limit) start = timer() msg = f"Annotating {vcf_in} with the VCF Annotator..." _logger.info(msg) diff --git a/src/ga4gh/vrs/extras/annotator/vcf.py b/src/ga4gh/vrs/extras/annotator/vcf.py index 13f132a1..9b55975d 100644 --- a/src/ga4gh/vrs/extras/annotator/vcf.py +++ b/src/ga4gh/vrs/extras/annotator/vcf.py @@ -119,12 +119,22 @@ class AbstractVcfAnnotator(abc.ABC): collect_alleles: bool = False - def __init__(self, data_proxy: _DataProxy, **kwargs) -> None: # noqa: ARG002 + def __init__( + self, + data_proxy: _DataProxy, + rle_seq_limit: int | None = RLE_SEQ_LIMIT, + **kwargs, # noqa: ARG002 + ) -> None: """Initialize the VCFAnnotator class. :param data_proxy: GA4GH sequence dataproxy instance. + :param rle_seq_limit: If RLE is set as the new state after normalization, this + sets the limit for the length of the `sequence` in VRS objects and in the + VRS_States INFO field. To exclude `sequence`, set to 0. For no limit, set + to `None`. Defaults to the `GA4GH_VRS_RLE_SEQ_LIMIT` setting. """ self.data_proxy = data_proxy + self.rle_seq_limit = rle_seq_limit self.tlr = AlleleTranslator(self.data_proxy) def should_collect_alleles(self, **kwargs) -> bool: # noqa: ARG002 @@ -407,6 +417,7 @@ def _get_vrs_object( vcf_coords, assembly_name=assembly, require_validation=require_validation, + rle_seq_limit=self.rle_seq_limit, ) except Exception: vrs_obj = None @@ -457,7 +468,7 @@ def _get_vrs_object( repeat_subunit_length = state.repeatSubunitLength # Only include sequence if within rle_seq_limit if state.sequence is not None and ( - RLE_SEQ_LIMIT is None or length <= RLE_SEQ_LIMIT + self.rle_seq_limit is None or length <= self.rle_seq_limit ): alt = state.sequence.root elif state_type == VrsType.LEN_EXPR: diff --git a/tests/extras/conftest.py b/tests/extras/conftest.py index ed33ec2e..c7a81482 100644 --- a/tests/extras/conftest.py +++ b/tests/extras/conftest.py @@ -13,6 +13,7 @@ def configured_modules(monkeypatch, request): import_module("ga4gh.vrs.normalize"), import_module("ga4gh.vrs.extras.translator"), import_module("ga4gh.vrs.extras.annotator.vcf"), + import_module("ga4gh.vrs.extras.annotator.cli"), ] original_namespaces = [vars(module).copy() for module in modules] try: diff --git a/tests/extras/test_annotate_vcf.py b/tests/extras/test_annotate_vcf.py index ef4adf61..a7236bba 100644 --- a/tests/extras/test_annotate_vcf.py +++ b/tests/extras/test_annotate_vcf.py @@ -1,6 +1,7 @@ """Ensure proper functionality of VCFAnnotator""" import gzip +import json import logging import os import re @@ -8,8 +9,10 @@ import pysam import pytest +from click.testing import CliRunner from ga4gh.vrs.dataproxy import DataProxyValidationError, SeqRepoRESTDataProxy +from ga4gh.vrs.extras.annotator import cli from ga4gh.vrs.extras.annotator.vcf import ( VcfAnnotator, VcfAnnotatorAbortError, @@ -341,6 +344,136 @@ def test_annotate_vcf_rle( assert vcr_cassette.all_played +@pytest.mark.vcr +@pytest.mark.parametrize( + ("configured_modules", "rle_seq_limit", "expected_sequence", "vcr_cassette_name"), + [ + (None, 0, None, "test_annotate_vcf_rle"), + (None, 4, None, "test_annotate_vcf_rle"), + ("4", 8, "CTTTCTTT", "test_annotate_vcf_rle"), + ("4", None, "CTTTCTTT", "test_annotate_vcf_rle"), + ("none", 4, None, "test_annotate_vcf_rle"), + ], + indirect=["configured_modules"], +) +def test_annotate_vcf_rle_seq_limit( + configured_modules, + rle_seq_limit, + expected_sequence, + rest_dataproxy_fn_scope, + vcr_cassette, + tmp_path: Path, +): + """Test that the annotator's ``rle_seq_limit`` overrides the configured default + for both the VRS_States INFO field and the VRS objects that are written out + """ + vcf_annotator = configured_modules[2].VcfAnnotator( + rest_dataproxy_fn_scope, rle_seq_limit=rle_seq_limit + ) + input_vcf = TEST_DATA_DIR / "test_rle.vcf" + output_vcf = tmp_path / "test_rle_seq_limit_output.vcf" + output_ndjson = tmp_path / "test_rle_seq_limit_output.ndjson" + + vcf_annotator.annotate( + input_vcf, output_vcf, vrs_attributes=True, output_ndjson_path=output_ndjson + ) + + with pysam.VariantFile(str(output_vcf)) as vcf: + # 1-102995989-CTTT-CTTTCTTT: ALT is an RLE with length 8 + duplication_variant = list(vcf)[1] + assert duplication_variant.info["VRS_Lengths"][-1] == 8 + assert duplication_variant.info["VRS_States"][-1] == (expected_sequence or ".") + + alleles = { + allele["id"]: allele + for allele in map(json.loads, output_ndjson.read_text().splitlines()) + } + dup_allele = alleles[duplication_variant.info["VRS_Allele_IDs"][-1]] + assert dup_allele["state"]["type"] == "ReferenceLengthExpression" + assert dup_allele["state"].get("sequence") == expected_sequence + if vcr_cassette.write_protected: + assert vcr_cassette.all_played + + +@pytest.mark.vcr +@pytest.mark.parametrize( + ("configured_modules", "rle_seq_limit", "expected_sequence", "vcr_cassette_name"), + [ + (None, "4", ".", "test_annotate_vcf_rle"), + ("4", None, ".", "test_annotate_vcf_rle"), + ("4", "8", "CTTTCTTT", "test_annotate_vcf_rle"), + ("4", "NoNe", "CTTTCTTT", "test_annotate_vcf_rle"), + ], + indirect=["configured_modules"], +) +def test_annotate_vcf_cli_rle_seq_limit( + configured_modules, + rle_seq_limit, + expected_sequence, + vcr_cassette, + tmp_path: Path, + monkeypatch, +): + """Test that ``--rle-seq-limit`` sets the limit used by ``vrs-annotate vcf``, + falling back to the configured default when it is not given + """ + input_vcf = (TEST_DATA_DIR / "test_rle.vcf").absolute() + output_vcf = tmp_path / "test_rle_cli_output.vcf" + seqrepo_rest_url = os.environ.get( + "SEQREPO_REST_URL", "http://localhost:5000/seqrepo" + ) + args = [ + "vcf", + str(input_vcf), + "--vcf-out", + str(output_vcf), + "--vrs-attributes", + "--dataproxy-uri", + f"seqrepo+{seqrepo_rest_url}", + "--silent", + ] + if rle_seq_limit is not None: + args += ["--rle-seq-limit", rle_seq_limit] + # Keep the CLI's log file out of the working tree + monkeypatch.chdir(tmp_path) + + result = CliRunner().invoke(configured_modules[3]._cli, args) + + assert result.exit_code == 0, result.output + with pysam.VariantFile(str(output_vcf)) as vcf: + duplication_variant = list(vcf)[1] + assert duplication_variant.info["VRS_States"][-1] == expected_sequence + if vcr_cassette.write_protected: + assert vcr_cassette.all_played + + +@pytest.mark.parametrize("rle_seq_limit", ["-1", "1.5", "invalid", ""]) +def test_annotate_vcf_cli_invalid_rle_seq_limit( + rle_seq_limit, tmp_path: Path, monkeypatch +): + """Test that ``--rle-seq-limit`` rejects values other than a non-negative + integer or 'none' + """ + input_vcf = (TEST_DATA_DIR / "test_rle.vcf").absolute() + monkeypatch.chdir(tmp_path) + + result = CliRunner().invoke( + cli._cli, + [ + "vcf", + str(input_vcf), + "--vcf-out", + str(tmp_path / "out.vcf"), + "--rle-seq-limit", + rle_seq_limit, + ], + ) + + assert result.exit_code == 2 + assert f"{rle_seq_limit!r} is not a non-negative integer or 'none'" in result.output + assert not (tmp_path / "out.vcf").exists() + + class FailingVcfAnnotator(VcfAnnotator): """Raise ``error`` when ``on_vrs_object`` reaches the given VCF coordinates"""