diff --git a/docs/extras/vcf_annotator.md b/docs/extras/vcf_annotator.md index 8187a526..8a495b9e 100644 --- a/docs/extras/vcf_annotator.md +++ b/docs/extras/vcf_annotator.md @@ -35,6 +35,18 @@ Or an alternate REST path: vrs-annotate vcf --dataproxy-uri="seqrepo+http://mylabwebsite.org/seqrepo" --vcf-out=out.vcf.gz input.vcf.gz ``` +### Output Options +At least one form of output must be declared. + +`--vcf-out` [PATH] +>Save location for the output annotated VCF (or `-` to write to stdout). + +`--pkl-out` [PATH] +>Save location for a PKL file mapping VRS IDs to VRS Alleles. + +`--jsonl-out` [PATH] +>Save location for a [JSON Lines](https://jsonlines.org/) file with one VRS Allele per line. `--ndjson-out` is a deprecated alias of this option, and will be removed in v3. + ### Configuring optional RLE sequences Set `GA4GH_VRS_RLE_SEQ_LIMIT` before starting Python or `vrs-annotate` to change diff --git a/src/ga4gh/vrs/extras/annotator/cli.py b/src/ga4gh/vrs/extras/annotator/cli.py index 4ebdb206..9a3e54a8 100644 --- a/src/ga4gh/vrs/extras/annotator/cli.py +++ b/src/ga4gh/vrs/extras/annotator/cli.py @@ -119,13 +119,20 @@ def convert( ), ) @click.option( - "--ndjson-out", + "--jsonl-out", required=False, type=click.Path(writable=True, allow_dash=False, path_type=Path), help=( - "Declare save location for output NDJSON file dump of VRS alleles. At least one form of output must be declared." + "Declare save location for output JSON Lines file dump of VRS alleles. At least one form of output must be declared." ), ) +@click.option( + "--ndjson-out", + required=False, + type=click.Path(writable=True, allow_dash=False, path_type=Path), + hidden=True, + help="Deprecated alias of --jsonl-out, which will be removed in v3.", +) @click.option( "--vrs-attributes", is_flag=True, @@ -169,6 +176,7 @@ def _annotate_vcf_cli( vcf_in: Path | str, vcf_out: Path | str | None, pkl_out: Path | None, + jsonl_out: Path | None, ndjson_out: Path | None, vrs_attributes: bool, dataproxy_uri: str, @@ -181,7 +189,7 @@ def _annotate_vcf_cli( $ vrs-annotate vcf input.vcf.gz --vcf-out output.vcf.gz --pkl-out vrs_objects.pkl - Note that at least one of --vcf-out, --pkl-out, or --ndjson-out must be selected and + Note that at least one of --vcf-out, --pkl-out, or --jsonl-out must be selected and defined; otherwise, this process will terminate immediately. Sequence data from a provider such as SeqRepo is required. Use the `--dataproxy-uri` @@ -198,6 +206,15 @@ def _annotate_vcf_cli( * seqrepo+file:///path/to/seqrepo/root * seqrepo+:../relative/path/to/seqrepo/root """ # noqa: D301 + if ndjson_out is not None: + if jsonl_out is not None: + msg = "--ndjson-out is a deprecated alias of --jsonl-out -- set only --jsonl-out" + raise click.UsageError(msg) + msg = "--ndjson-out is deprecated and will be removed in v3. Use --jsonl-out instead." + click.echo(f"Warning: {msg}", err=True) + _logger.warning(msg) + jsonl_out = ndjson_out + data_proxy = create_dataproxy(dataproxy_uri) annotator = VcfAnnotator(data_proxy) start = timer() @@ -213,10 +230,10 @@ def _annotate_vcf_cli( compute_for_ref=(not skip_ref), require_validation=require_validation, output_pkl_path=pkl_out, - output_ndjson_path=ndjson_out, + output_jsonl_path=jsonl_out, ) except VcfAnnotatorArgsError: - msg = "No VCF, PKL, or NDJSON output path provided -- must set at least one of --vcf-out, --pkl-out, or --ndjson-out" + msg = "No VCF, PKL, or JSON Lines output path provided -- must set at least one of --vcf-out, --pkl-out, or --jsonl-out" if not silent: click.echo(msg) _logger.exception(msg) diff --git a/src/ga4gh/vrs/extras/annotator/vcf.py b/src/ga4gh/vrs/extras/annotator/vcf.py index 13f132a1..523137c3 100644 --- a/src/ga4gh/vrs/extras/annotator/vcf.py +++ b/src/ga4gh/vrs/extras/annotator/vcf.py @@ -3,11 +3,13 @@ import abc import logging import pickle +import warnings from enum import Enum from pathlib import Path from typing import Literal import pysam +from typing_extensions import deprecated from ga4gh.core.identifiers import ( VrsObjectIdentifierIs, @@ -91,19 +93,35 @@ def dump_alleles_to_pkl(alleles: list[Allele], output_pkl_path: Path) -> None: pickle.dump(allele_dict, f) -def dump_alleles_to_ndjson( - allele_collection: list[Allele], output_ndjson_path: Path +def dump_alleles_to_jsonl( + allele_collection: list[Allele], output_jsonl_path: Path ) -> None: - """Create NDJSON dump of all alleles ingested from VCF + """Create JSON Lines dump of all alleles ingested from VCF - :param alleles: all alleles + constructed + annotated during VCF ingestion - :param output_ndjson_path: location to save NDJSON file to + :param allele_collection: all alleles constructed + annotated during VCF ingestion + :param output_jsonl_path: location to save JSON Lines file to """ - with output_ndjson_path.open("w") as f: + with output_jsonl_path.open("w") as f: for allele in allele_collection: f.write(allele.model_dump_json(exclude_none=True) + "\n") +@deprecated( + "dump_alleles_to_ndjson is deprecated and will be removed in v3. Use dump_alleles_to_jsonl instead." +) +def dump_alleles_to_ndjson( + allele_collection: list[Allele], output_ndjson_path: Path +) -> None: + """Create JSON Lines dump of all alleles ingested from VCF + + Deprecated alias of ``dump_alleles_to_jsonl``. + + :param allele_collection: all alleles constructed + annotated during VCF ingestion + :param output_ndjson_path: location to save JSON Lines file to + """ + dump_alleles_to_jsonl(allele_collection, output_ndjson_path) + + class AbstractVcfAnnotator(abc.ABC): """Abstract class for VCF annotation with VRS. @@ -557,16 +575,18 @@ class VcfAnnotator(AbstractVcfAnnotator): collect_alleles = True pkl_arg_name = "output_pkl_path" + jsonl_arg_name = "output_jsonl_path" + # Deprecated alias of ``jsonl_arg_name``, which will be removed in v3 ndjson_arg_name = "output_ndjson_path" def should_collect_alleles(self, **kwargs) -> bool: """Inhibit allele collection parameter if no means of output are given. :kwparam output_pkl_path: Optional path to output PKL dump of all alleles - :kwparam output_ndjson_path: Optional path to output NDJSON dump of all alleles + :kwparam output_jsonl_path: Optional path to output JSON Lines dump of all alleles :return: ``True`` if at least one of the output path args is ``True`` """ - return bool(kwargs.get("output_pkl_path") or kwargs.get("output_ndjson_path")) + return bool(kwargs.get(self.pkl_arg_name) or kwargs.get(self.jsonl_arg_name)) @use_ga4gh_compute_identifier_when(VrsObjectIdentifierIs.MISSING) def annotate( @@ -580,7 +600,7 @@ def annotate( **kwargs, ) -> None: """Given a VCF, produce an output VCF annotated with VRS allele IDs, and/or - a PKL or NDJSON dump of the corresponding VRS objects. + a PKL or JSON Lines dump of the corresponding VRS objects. :param input_vcf_path: Location of input VCF :param output_vcf_path: The path for the output VCF file @@ -595,9 +615,24 @@ def annotate( validation checks fail, although all instances of failed validation are logged as warnings regardless. :kwparam output_pkl_path: Optional path to output PKL dump of all alleles - :kwparam output_ndjson_path: Optional path to output NDJSON dump of all alleles - :raise VCFAnnotatorError: if no output formats are selected + :kwparam output_jsonl_path: Optional path to output JSON Lines dump of all + alleles + :kwparam output_ndjson_path: Deprecated alias of `output_jsonl_path`, which + will be removed in v3 + :raise VCFAnnotatorError: if no output formats are selected, or if both + `output_jsonl_path` and `output_ndjson_path` are given """ + output_ndjson_path = kwargs.pop(self.ndjson_arg_name, None) + if output_ndjson_path is not None: + warnings.warn( + f"`{self.ndjson_arg_name}` is deprecated and will be removed in v3. Use `{self.jsonl_arg_name}` instead.", + DeprecationWarning, + stacklevel=3, # skip the identifier-computation context decorator + ) + if kwargs.get(self.jsonl_arg_name) is not None: + msg = f"`{self.ndjson_arg_name}` is a deprecated alias of `{self.jsonl_arg_name}` -- pass only `{self.jsonl_arg_name}` to annotate()." + raise VcfAnnotatorArgsError(msg) + kwargs[self.jsonl_arg_name] = output_ndjson_path return super().annotate( input_vcf_path, output_vcf_path, @@ -609,20 +644,20 @@ def annotate( ) def raise_for_output_args(self, output_vcf_path: Path | None, **kwargs) -> None: - """Raise an exception if no output (VCF, PKL, NDJSON) appears to be configured - or declared. + """Raise an exception if no output (VCF, PKL, JSON Lines) appears to be + configured or declared. :param output_vcf_path: VCF output path arg passed to `annotate()` :kwparam output_pkl_path: optional path to PKL output - :kwparam output_ndjson_path: optional path to NDJSON output + :kwparam output_jsonl_path: optional path to JSON Lines output :raise VCFAnnotatorArgsError: if no output args are given """ if ( output_vcf_path is None and kwargs.get(self.pkl_arg_name) is None - and kwargs.get(self.ndjson_arg_name) is None + and kwargs.get(self.jsonl_arg_name) is None ): - msg = f"No VCF, PKL, or NDJSON output path provided -- must pass at least one of `output_vcf_path`, `{self.pkl_arg_name}`, `{self.ndjson_arg_name}` to annotate()." + msg = f"No VCF, PKL, or JSON Lines output path provided -- must pass at least one of `output_vcf_path`, `{self.pkl_arg_name}`, `{self.jsonl_arg_name}` to annotate()." raise VcfAnnotatorArgsError(msg) def on_vrs_object( @@ -655,6 +690,6 @@ def on_vrs_object_collection( if output_pkl_path is not None: dump_alleles_to_pkl(vrs_alleles_collection, output_pkl_path) - 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) + output_jsonl_path = kwargs.get(self.jsonl_arg_name) + if output_jsonl_path is not None: + dump_alleles_to_jsonl(vrs_alleles_collection, output_jsonl_path) diff --git a/tests/extras/test_annotate_vcf.py b/tests/extras/test_annotate_vcf.py index ef4adf61..12243155 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,12 +9,20 @@ import pysam import pytest +from click.testing import CliRunner -from ga4gh.vrs.dataproxy import DataProxyValidationError, SeqRepoRESTDataProxy +from ga4gh.vrs.dataproxy import ( + DataProxyValidationError, + SeqRepoDataProxy, + SeqRepoRESTDataProxy, +) +from ga4gh.vrs.extras.annotator.cli import _cli from ga4gh.vrs.extras.annotator.vcf import ( VcfAnnotator, VcfAnnotatorAbortError, + VcfAnnotatorArgsError, VcfAnnotatorError, + dump_alleles_to_ndjson, ) from ga4gh.vrs.models import Allele @@ -187,11 +196,138 @@ def test_annotate_vcf_vcf_only( assert not Path(output_vrs_pkl).exists() +def check_jsonl_output(output_jsonl: Path, require_validation: bool = True): + """Check the JSON Lines dump of the alleles annotated from ``test_vcf_input.vcf``""" + with output_jsonl.open() as f: + alleles = [Allele(**json.loads(line)) for line in f] + # REF and ALT alleles for all records, except a `*` ALT, an invalid ALT and, if + # validation is required, a record with a reference mismatch + assert len(alleles) == (14 if require_validation else 16) + assert alleles[0].id == "ga4gh:VA.esmv8nARRRdSysDFuIErJxRAdUSVsWNE" + assert alleles[1].id == "ga4gh:VA.b9AIUegs1SOYO7nKY8l01yllkyUns-u4" + + +def test_annotate_vcf_jsonl_only( + dataproxy: SeqRepoDataProxy, input_vcf: Path, tmp_path: Path +): + output_jsonl = tmp_path / "test_vcf_jsonl_only.jsonl" + + VcfAnnotator(dataproxy).annotate(input_vcf, output_jsonl_path=output_jsonl) + check_jsonl_output(output_jsonl) + assert list(tmp_path.iterdir()) == [output_jsonl] + + +def test_annotate_vcf_ndjson_deprecated( + dataproxy: SeqRepoDataProxy, input_vcf: Path, tmp_path: Path +): + """Test that the deprecated `output_ndjson_path` arg still writes JSON Lines""" + output_jsonl = tmp_path / "test_vcf_ndjson_deprecated.ndjson" + vcf_annotator = VcfAnnotator(dataproxy) + + with pytest.warns( + DeprecationWarning, match="`output_ndjson_path` is deprecated" + ) as warnings_record: + vcf_annotator.annotate(input_vcf, output_ndjson_path=output_jsonl) + # Warning points at the caller of annotate() + assert warnings_record[0].filename == __file__ + check_jsonl_output(output_jsonl) + + with ( + pytest.warns(DeprecationWarning), + pytest.raises( + VcfAnnotatorArgsError, + match="`output_ndjson_path` is a deprecated alias of `output_jsonl_path`", + ), + ): + vcf_annotator.annotate( + input_vcf, + output_jsonl_path=tmp_path / "test_vcf_both.jsonl", + output_ndjson_path=tmp_path / "test_vcf_both.ndjson", + ) + + +def test_dump_alleles_to_ndjson_deprecated(tmp_path: Path): + output_jsonl = tmp_path / "test_dump.ndjson" + allele = Allele( + location={ + "sequenceReference": { + "refgetAccession": "SQ.IIB53T8CNeJJdUqzn9V_JnRtQadwWCbl" + }, + "start": 82663, + "end": 82664, + }, + state={"type": "LiteralSequenceExpression", "sequence": "T"}, + ) + + with pytest.warns(DeprecationWarning, match="dump_alleles_to_jsonl"): + dump_alleles_to_ndjson([allele], output_jsonl) + assert output_jsonl.read_text() == allele.model_dump_json(exclude_none=True) + "\n" + + +@pytest.fixture +def cli_dataproxy_uri() -> str: + """Provide a data proxy URI for the local SeqRepo used by the `dataproxy` fixture""" + root_dir = os.environ.get("SEQREPO_ROOT_DIR", "/usr/local/share/seqrepo/latest") + return f"seqrepo+file://{Path(root_dir).absolute()}" + + +@pytest.mark.parametrize("output_option", ["--jsonl-out", "--ndjson-out"]) +def test_annotate_vcf_cli_jsonl( + cli_dataproxy_uri: str, + input_vcf: Path, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + output_option: str, +): + """Test JSON Lines output from the CLI, including the deprecated `--ndjson-out`""" + input_vcf = input_vcf.absolute() + monkeypatch.chdir(tmp_path) # CLI writes a log file to the working directory + output_jsonl = tmp_path / "test_vcf_cli.jsonl" + + result = CliRunner().invoke( + _cli, + [ + "vcf", + str(input_vcf), + f"--dataproxy-uri={cli_dataproxy_uri}", + output_option, + str(output_jsonl), + ], + ) + assert result.exit_code == 0, result.output + deprecation_msg = "--ndjson-out is deprecated and will be removed in v3" + assert (deprecation_msg in result.output) == (output_option == "--ndjson-out") + check_jsonl_output(output_jsonl, require_validation=False) + + +def test_annotate_vcf_cli_jsonl_and_ndjson( + input_vcf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + input_vcf = input_vcf.absolute() + monkeypatch.chdir(tmp_path) + + result = CliRunner().invoke( + _cli, + [ + "vcf", + str(input_vcf), + "--jsonl-out", + str(tmp_path / "test_vcf_cli.jsonl"), + "--ndjson-out", + str(tmp_path / "test_vcf_cli.ndjson"), + ], + ) + assert result.exit_code == 2 + assert "--ndjson-out is a deprecated alias of --jsonl-out" in result.output + assert not (tmp_path / "test_vcf_cli.jsonl").exists() + assert not (tmp_path / "test_vcf_cli.ndjson").exists() + + @pytest.mark.vcr def test_annotate_vcf_input_validation(vcf_annotator: VcfAnnotator, input_vcf: Path): with pytest.raises( VcfAnnotatorError, - match="No VCF, PKL, or NDJSON output path provided -- must pass at least one of `output_vcf_path`, `output_pkl_path`, `output_ndjson_path` to annotate().", + match="No VCF, PKL, or JSON Lines output path provided -- must pass at least one of `output_vcf_path`, `output_pkl_path`, `output_jsonl_path` to annotate().", ): vcf_annotator.annotate(input_vcf)