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
27 changes: 23 additions & 4 deletions docs/extras/vcf_annotator.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,40 @@ 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:

```shell
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]

Expand Down
36 changes: 35 additions & 1 deletion src/ga4gh/vrs/extras/annotator/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
15 changes: 13 additions & 2 deletions src/ga4gh/vrs/extras/annotator/vcf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions tests/extras/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
133 changes: 133 additions & 0 deletions tests/extras/test_annotate_vcf.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
"""Ensure proper functionality of VCFAnnotator"""

import gzip
import json
import logging
import os
import re
from pathlib import Path

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,
Expand Down Expand Up @@ -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"""

Expand Down
Loading