# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""VCF parser interface backed by the Rust noodles-vcf parser."""
from __future__ import annotations
from pathlib import Path
from attr import define, field, setters
from ensembl.vep.common import format_region_string
from ensembl.vep.parsers.parser import Parser
from ensembl.vep.ensembl_vep_core import ( # noqa: F401,F403 pylint: disable=E0401,E0611
VCFParser as _RustVCFParser,
VCFRecord,
)
__all__ = ["VCFParser", "VCFRecord"]
[docs]
@define(kw_only=True, auto_attribs=True)
class VCFParser(Parser[VCFRecord]):
"""Parser facade for VCF files.
Attributes:
format: The format of the file being parsed.
file_path (str | Path | None): The path to the file being parsed.
tabix_path (str): The path to the tabix executable.
mode (str): The reader mode, either "auto", "query" or "sequential".
Default is "auto", which will attempt to use "query" mode
and fall back to "sequential" if the file is not indexed.
"""
format: str = field(init=False, default="vcf")
file_path: str | Path | None = field(default=None)
tabix_path: str | Path | None = field(default="tabix")
mode: str = field(default="auto", on_setattr=setters.frozen)
_parser: _RustVCFParser = field(init=False, repr=False)
def __attrs_post_init__(self) -> None:
self._parser = _RustVCFParser(
str(self.file_path) if self.file_path is not None else None,
str(self.tabix_path) if self.tabix_path is not None else None,
self.mode,
)
@property
def metadata(self) -> dict:
"""Return parsed file metadata.
Returns:
dict: The metadata dictionary.
"""
return self._metadata
@property
def _metadata(self) -> dict:
"""Metadata dictionary containing VCF directives and header lines.
Returns:
dict: A dictionary with keys "file_format", "info", "filter", "format", "alt", "contig",
"samples", "other" and "header" (the file's header lines verbatim)
"""
return dict(self._parser.metadata)
@property
def reader_mode(self) -> str:
"""Return the configured reader mode."""
return self._parser.reader_mode
[docs]
def open(self, file_path: str | Path, mode: str = "auto") -> VCFParser:
"""Open a VCF file.
Args:
file_path (str | Path): The path to the VCF file to be parsed.
mode (str): The mode in which to open the file.
Returns:
VCFParser: The parser instance.
"""
self.file_path = file_path
self._clear_metadata_cache()
self._parser.open(str(file_path), mode)
return self
[docs]
def close(self) -> None:
"""Close the parser."""
self._parser.close()
self._clear_metadata_cache()
[docs]
def seek(
self,
region: str | None = None,
*,
seq_region_name: str | None = None,
start: int | None = None,
end: int | None = None,
) -> bool:
"""Seek to a region and make next() stream matching records.
Args:
region (str | None): The region to seek to, in the format "chr:start-end".
seq_region_name (str | None): The name of the region to seek to..
start (int | None): The start position of the region to seek to.
end (int | None): The end position of the region to seek to.
Returns:
bool: True if the seek was successful, False otherwise.
"""
return self._parser.seek(
format_region_string(region, seq_region_name=seq_region_name, start=start, end=end)
)
[docs]
def next(self) -> VCFRecord | None:
"""Return the next VCF record, or ``None`` at EOF.
Returns:
VCFRecord | None: The next VCF record,
or None if the end of the file.
"""
return self._parser.next()
[docs]
def records(self, limit: int | None = 10000) -> list[VCFRecord]:
"""Return records from the current stream position.
Args:
limit (int | None): The maximum number of records to return. Default is 10000.
Returns:
list[VCFRecord]: A list of VCF records.
"""
return self._parser.records(limit)
[docs]
def raw_lines(self, limit: int | None = 10000) -> list[str]:
"""Return record lines from the current stream position without line endings.
The same stream as ``records``, read one step earlier: each line is returned before
anything parses it, for a caller that wants the input's own text rather than a record.
Args:
limit (int | None): The maximum number of lines to return. Default is 10000.
Returns:
list[str]: The record lines, in input order.
"""
return self._parser.raw_lines(limit)
def _clear_metadata_cache(self) -> None:
try:
del self._metadata
except AttributeError:
pass
[docs]
@staticmethod
def parse_text(data: str, limit: int | None = None) -> list[VCFRecord]:
"""Parse VCF records from text.
Args:
data (str): The VCF text to parse.
limit (int | None): The maximum number of records to return. If None, return all records.
Returns:
list[VCFRecord]: A list of VCF records.
"""
return _RustVCFParser.parse_text(data, limit)
[docs]
@staticmethod
def record_count(file_path: str | Path, scan: bool = False) -> int | None:
"""Return the declared VCF record count, if available.
The count comes from the file's index, which answers in one small read. Without an index
there is no count unless ``scan`` is set, which reads the whole file; on an input of a
billion lines that pass dominates a run, so a caller that only wants the count for
progress reporting leaves it off and does without.
Args:
file_path (str | Path): The path to the VCF file to count.
scan (bool): Whether to count by reading the file when no index declares it.
Default is False.
Returns:
int | None: The record count, or None when no index declares it and ``scan`` is False.
"""
return _RustVCFParser.record_count(str(file_path), scan)
[docs]
@staticmethod
def parse_file(file_path: str | Path, limit: int | None = None) -> list[VCFRecord]:
"""Parse VCF records from a file.
Args:
file_path (str | Path): The path to the VCF file to parse.
limit (int | None): The maximum number of records to return. If None, return all records.
Returns:
list[VCFRecord]: A list of VCF records.
"""
return _RustVCFParser.parse_file(str(file_path), limit)