Coverage for src/python/ensembl/vep/parsers/gtf.py: 100%
56 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""GTF parser interface backed by the Rust noodles-gtf parser."""
16from __future__ import annotations
18from collections.abc import Iterable
19from pathlib import Path
20from attr import define, field, setters
22from ensembl.vep.common import format_region_string
23from ensembl.vep.parsers.parser import Parser
24from ensembl.vep.ensembl_vep_core import ( # noqa: F401,F403 pylint: disable=E0401,E0611
25 GTFParser as _RustGTFParser,
26 GTFRecord,
27)
29__all__ = ["GTFParser", "GTFRecord"]
32@define(kw_only=True, auto_attribs=True)
33class GTFParser(Parser[GTFRecord]):
34 """Parser facade for GTF files.
36 Attributes:
37 format (str): The format of the file being parsed.
38 file_path (str | Path | None): The path to the file being parsed.
39 tabix_path (str): The path to the tabix executable.
40 mode (str): The reader mode, either "auto", "query" or "sequential".
41 Default is "auto", which will attempt to use "query" mode
42 and fall back to "sequential" if the file is not indexed.
43 """
45 format: str = field(init=False, default="gtf")
46 file_path: str | Path | None = field(default=None)
47 tabix_path: str | Path | None = field(default="tabix")
48 mode: str = field(default="auto", on_setattr=setters.frozen)
49 _parser: _RustGTFParser = field(init=False, repr=False)
51 def __attrs_post_init__(self) -> None:
52 self._parser = _RustGTFParser(
53 str(self.file_path) if self.file_path is not None else None,
54 str(self.tabix_path) if self.tabix_path is not None else None,
55 self.mode,
56 )
58 @property
59 def metadata(self) -> dict:
60 """Return parsed file metadata.
62 Returns:
63 dict: The metadata dictionary.
64 """
66 return self._metadata
68 @property
69 def _metadata(self) -> dict:
70 """Metadata dictionary containing GTF header lines.
72 Returns:
73 dict: A dictionary with keys "header".
74 """
76 return dict(self._parser.metadata)
78 @property
79 def reader_mode(self) -> str:
80 """Return the configured reader mode."""
82 return self._parser.reader_mode
84 @property
85 def index_sequence_names(self) -> list[str]:
86 """Return reference sequence names declared by the tabix index.
88 Empty when the file is unopened, read sequentially, or falls back to the system
89 ``tabix`` executable.
91 Returns:
92 list[str]: The reference sequence names the index declares.
93 """
95 return self._parser.index_sequence_names
97 def open(self, file_path: str | Path, mode: str = "auto") -> GTFParser:
98 """Open a GTF file.
100 Args:
101 file_path (str | Path): The path to the GTF file to be parsed.
103 Returns:
104 GTFParser: The parser instance.
105 """
107 self.file_path = file_path
108 self._clear_metadata_cache()
109 self._parser.open(str(file_path), mode)
110 return self
112 def close(self) -> None:
113 """Close the parser."""
115 self._parser.close()
116 self._clear_metadata_cache()
118 def seek(
119 self,
120 region: str | None = None,
121 *,
122 seq_region_name: str | None = None,
123 start: int | None = None,
124 end: int | None = None,
125 ) -> bool:
126 """Seek to a region and make next() stream matching records.
128 Args:
129 region (str | None): The region to seek to, in the format "chr:start-end".
130 seq_region_name (str | None): The name of the region to seek to..
131 start (int | None): The start position of the region to seek to.
132 end (int | None): The end position of the region to seek to.
134 Returns:
135 bool: True if the seek was successful, False otherwise.
136 """
138 return self._parser.seek(
139 format_region_string(region, seq_region_name=seq_region_name, start=start, end=end)
140 )
142 def next(self) -> GTFRecord | None:
143 """Return the next GTF record, or ``None`` at EOF.
145 Returns:
146 GTFRecord | None: The next GTF record,
147 or None if the end of the file reached.
148 """
150 return self._parser.next()
152 def records(
153 self, limit: int | None = 10000, feature_types: Iterable[str] | None = None
154 ) -> list[GTFRecord]:
155 """Return records from the current stream position.
157 Args:
158 limit (int | None): The maximum number of records to return. Default is 10000.
159 feature_types (Iterable[str] | None): When given, only rows whose column 3 matches one
160 of these values (case-insensitively) are returned. The Rust side applies this
161 before a non-matching line is parsed into a record or converted into a Python
162 object.
164 Returns:
165 list[GTFRecord]: A list of GTF records.
166 """
168 return self._parser.records(limit, None if feature_types is None else list(feature_types))
170 def raw_lines(self, limit: int | None = 10000) -> list[str]:
171 """Return record lines from the current stream position without line endings.
173 The same stream as ``records``, read one step earlier: each line is returned before
174 anything parses it, for a caller that wants the input's own text rather than a record.
176 Args:
177 limit (int | None): The maximum number of lines to return. Default is 10000.
179 Returns:
180 list[str]: The record lines, in input order.
181 """
183 return self._parser.raw_lines(limit)
185 def _clear_metadata_cache(self) -> None:
186 try:
187 del self._metadata
188 except AttributeError:
189 pass
191 @staticmethod
192 def parse_text(data: str, limit: int | None = None) -> list[GTFRecord]:
193 """Parse GTF records from text.
195 Args:
196 data (str): The GTF text to parse.
197 limit (int | None): The maximum number of records to return. If None, return all records.
199 Returns:
200 list[GTFRecord]: A list of GTF records.
201 """
203 return _RustGTFParser.parse_text(data, limit)
205 @staticmethod
206 def parse_file(file_path: str | Path, limit: int | None = None) -> list[GTFRecord]:
207 """Parse GTF records from a file.
209 Args:
210 file_path (str | Path): The path to the GTF file to parse.
211 limit (int | None): The maximum number of records to return. If None, return all records.
213 Returns:
214 list[GTFRecord]: A list of GTF records.
215 """
217 return _RustGTFParser.parse_file(str(file_path), limit)