Coverage for src/python/ensembl/vep/parsers/gff3.py: 100%

56 statements  

« 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"""GFF3 parser interface backed by the Rust noodles-gff parser.""" 

15 

16from __future__ import annotations 

17 

18from collections.abc import Iterable 

19from pathlib import Path 

20from attr import define, field, setters 

21 

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 GFF3Parser as _RustGFF3Parser, 

26 GFF3Record, 

27) 

28 

29__all__ = ["GFF3Parser", "GFF3Record"] 

30 

31 

32@define(kw_only=True, auto_attribs=True) 

33class GFF3Parser(Parser[GFF3Record]): 

34 """Parser facade for GFF3 files. 

35 

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 """ 

44 

45 format: str = field(init=False, default="gff3") 

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: _RustGFF3Parser = field(init=False, repr=False) 

50 

51 def __attrs_post_init__(self) -> None: 

52 self._parser = _RustGFF3Parser( 

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 ) 

57 

58 @property 

59 def metadata(self) -> dict: 

60 """Return parsed file metadata. 

61 

62 Returns: 

63 dict: The metadata dictionary. 

64 """ 

65 

66 return self._metadata 

67 

68 @property 

69 def _metadata(self) -> dict: 

70 """Metadata dictionary containing GFF3 directives and header lines. 

71 

72 Returns: 

73 dict: A dictionary with keys "header" and specific directives (e.g. "gff-version"). 

74 """ 

75 

76 return dict(self._parser.metadata) 

77 

78 @property 

79 def reader_mode(self) -> str: 

80 """Return the configured reader mode.""" 

81 

82 return self._parser.reader_mode 

83 

84 @property 

85 def index_sequence_names(self) -> list[str]: 

86 """Return reference sequence names declared by the tabix index. 

87 

88 Empty when the file is unopened, read sequentially, or falls back to the system 

89 ``tabix`` executable. 

90 

91 Returns: 

92 list[str]: The reference sequence names the index declares. 

93 """ 

94 

95 return self._parser.index_sequence_names 

96 

97 def open(self, file_path: str | Path, mode: str = "auto") -> GFF3Parser: 

98 """Open a GFF3 file. 

99 

100 Args: 

101 file_path (str | Path): The path to the GFF3 file to be parsed. 

102 mode (str): The mode in which to open the file. 

103 

104 Returns: 

105 GFF3Parser: The parser instance. 

106 """ 

107 

108 self.file_path = file_path 

109 self._clear_metadata_cache() 

110 self._parser.open(str(file_path), mode) 

111 return self 

112 

113 def close(self) -> None: 

114 """Close the parser.""" 

115 

116 self._parser.close() 

117 self._clear_metadata_cache() 

118 

119 def seek( 

120 self, 

121 region: str | None = None, 

122 *, 

123 seq_region_name: str | None = None, 

124 start: int | None = None, 

125 end: int | None = None, 

126 ) -> bool: 

127 """Seek to a region and make next() stream matching records. 

128 

129 Args: 

130 region (str | None): The region to seek to, in the format "chr:start-end". 

131 seq_region_name (str | None): The name of the region to seek to.. 

132 start (int | None): The start position of the region to seek to. 

133 end (int | None): The end position of the region to seek to. 

134 

135 Returns: 

136 bool: True if the seek was successful, False otherwise. 

137 """ 

138 

139 return self._parser.seek( 

140 format_region_string(region, seq_region_name=seq_region_name, start=start, end=end) 

141 ) 

142 

143 def next(self) -> GFF3Record | None: 

144 """Return the next GFF3 record, or ``None`` at EOF or ``##FASTA``. 

145 

146 Returns: 

147 GFF3Record | None: The next GFF3 record, 

148 or None if the end of the file or a ##FASTA directive is reached. 

149 """ 

150 

151 return self._parser.next() 

152 

153 def records( 

154 self, limit: int | None = 10000, feature_types: Iterable[str] | None = None 

155 ) -> list[GFF3Record]: 

156 """Return records from the current stream position. 

157 

158 Args: 

159 limit (int | None): The maximum number of records to return. Default is 10000. 

160 feature_types (Iterable[str] | None): When given, only rows whose column 3 matches one 

161 of these values (case-insensitively) are returned. The Rust side applies this 

162 before a non-matching line is parsed into a record or converted into a Python 

163 object. 

164 

165 Returns: 

166 list[GFF3Record]: A list of GFF3 records. 

167 """ 

168 

169 return self._parser.records(limit, None if feature_types is None else list(feature_types)) 

170 

171 def raw_lines(self, limit: int | None = 10000) -> list[str]: 

172 """Return record lines from the current stream position without line endings. 

173 

174 The same stream as ``records``, read one step earlier: each line is returned before 

175 anything parses it, for a caller that wants the input's own text rather than a record. 

176 

177 Args: 

178 limit (int | None): The maximum number of lines to return. Default is 10000. 

179 

180 Returns: 

181 list[str]: The record lines, in input order. 

182 """ 

183 

184 return self._parser.raw_lines(limit) 

185 

186 def _clear_metadata_cache(self) -> None: 

187 try: 

188 del self._metadata 

189 except AttributeError: 

190 pass 

191 

192 @staticmethod 

193 def parse_text(data: str, limit: int | None = None) -> list[GFF3Record]: 

194 """Parse GFF3 records from text. 

195 

196 Args: 

197 data (str): The GFF3 text to parse. 

198 limit (int | None): The maximum number of records to return. If None, return all records. 

199 

200 Returns: 

201 list[GFF3Record]: A list of GFF3 records. 

202 """ 

203 

204 return _RustGFF3Parser.parse_text(data, limit) 

205 

206 @staticmethod 

207 def parse_file(file_path: str | Path, limit: int | None = None) -> list[GFF3Record]: 

208 """Parse GFF3 records from a file. 

209 

210 Args: 

211 file_path (str | Path): The path to the GFF3 file to parse. 

212 limit (int | None): The maximum number of records to return. If None, return all records. 

213 

214 Returns: 

215 list[GFF3Record]: A list of GFF3 records. 

216 """ 

217 

218 return _RustGFF3Parser.parse_file(str(file_path), limit)