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

55 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"""VCF parser interface backed by the Rust noodles-vcf parser.""" 

15 

16from __future__ import annotations 

17 

18from pathlib import Path 

19from attr import define, field, setters 

20 

21from ensembl.vep.common import format_region_string 

22from ensembl.vep.parsers.parser import Parser 

23from ensembl.vep.ensembl_vep_core import ( # noqa: F401,F403 pylint: disable=E0401,E0611 

24 VCFParser as _RustVCFParser, 

25 VCFRecord, 

26) 

27 

28__all__ = ["VCFParser", "VCFRecord"] 

29 

30 

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

32class VCFParser(Parser[VCFRecord]): 

33 """Parser facade for VCF files. 

34 

35 Attributes: 

36 format: The format of the file being parsed. 

37 file_path (str | Path | None): The path to the file being parsed. 

38 tabix_path (str): The path to the tabix executable. 

39 mode (str): The reader mode, either "auto", "query" or "sequential". 

40 Default is "auto", which will attempt to use "query" mode 

41 and fall back to "sequential" if the file is not indexed. 

42 """ 

43 

44 format: str = field(init=False, default="vcf") 

45 file_path: str | Path | None = field(default=None) 

46 tabix_path: str | Path | None = field(default="tabix") 

47 mode: str = field(default="auto", on_setattr=setters.frozen) 

48 _parser: _RustVCFParser = field(init=False, repr=False) 

49 

50 def __attrs_post_init__(self) -> None: 

51 self._parser = _RustVCFParser( 

52 str(self.file_path) if self.file_path is not None else None, 

53 str(self.tabix_path) if self.tabix_path is not None else None, 

54 self.mode, 

55 ) 

56 

57 @property 

58 def metadata(self) -> dict: 

59 """Return parsed file metadata. 

60 

61 Returns: 

62 dict: The metadata dictionary. 

63 """ 

64 

65 return self._metadata 

66 

67 @property 

68 def _metadata(self) -> dict: 

69 """Metadata dictionary containing VCF directives and header lines. 

70 

71 Returns: 

72 dict: A dictionary with keys "file_format", "info", "filter", "format", "alt", "contig", 

73 "samples", "other" and "header" (the file's header lines verbatim) 

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 def open(self, file_path: str | Path, mode: str = "auto") -> VCFParser: 

85 """Open a VCF file. 

86 

87 Args: 

88 file_path (str | Path): The path to the VCF file to be parsed. 

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

90 

91 Returns: 

92 VCFParser: The parser instance. 

93 """ 

94 

95 self.file_path = file_path 

96 self._clear_metadata_cache() 

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

98 return self 

99 

100 def close(self) -> None: 

101 """Close the parser.""" 

102 

103 self._parser.close() 

104 self._clear_metadata_cache() 

105 

106 def seek( 

107 self, 

108 region: str | None = None, 

109 *, 

110 seq_region_name: str | None = None, 

111 start: int | None = None, 

112 end: int | None = None, 

113 ) -> bool: 

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

115 

116 Args: 

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

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

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

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

121 

122 Returns: 

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

124 """ 

125 

126 return self._parser.seek( 

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

128 ) 

129 

130 def next(self) -> VCFRecord | None: 

131 """Return the next VCF record, or ``None`` at EOF. 

132 

133 Returns: 

134 VCFRecord | None: The next VCF record, 

135 or None if the end of the file. 

136 """ 

137 

138 return self._parser.next() 

139 

140 def records(self, limit: int | None = 10000) -> list[VCFRecord]: 

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

142 

143 Args: 

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

145 

146 Returns: 

147 list[VCFRecord]: A list of VCF records. 

148 """ 

149 

150 return self._parser.records(limit) 

151 

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

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

154 

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

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

157 

158 Args: 

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

160 

161 Returns: 

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

163 """ 

164 

165 return self._parser.raw_lines(limit) 

166 

167 def _clear_metadata_cache(self) -> None: 

168 try: 

169 del self._metadata 

170 except AttributeError: 

171 pass 

172 

173 @staticmethod 

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

175 """Parse VCF records from text. 

176 

177 Args: 

178 data (str): The VCF text to parse. 

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

180 

181 Returns: 

182 list[VCFRecord]: A list of VCF records. 

183 """ 

184 

185 return _RustVCFParser.parse_text(data, limit) 

186 

187 @staticmethod 

188 def record_count(file_path: str | Path, scan: bool = False) -> int | None: 

189 """Return the declared VCF record count, if available. 

190 

191 The count comes from the file's index, which answers in one small read. Without an index 

192 there is no count unless ``scan`` is set, which reads the whole file; on an input of a 

193 billion lines that pass dominates a run, so a caller that only wants the count for 

194 progress reporting leaves it off and does without. 

195 

196 Args: 

197 file_path (str | Path): The path to the VCF file to count. 

198 scan (bool): Whether to count by reading the file when no index declares it. 

199 Default is False. 

200 

201 Returns: 

202 int | None: The record count, or None when no index declares it and ``scan`` is False. 

203 """ 

204 

205 return _RustVCFParser.record_count(str(file_path), scan) 

206 

207 @staticmethod 

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

209 """Parse VCF records from a file. 

210 

211 Args: 

212 file_path (str | Path): The path to the VCF file to parse. 

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

214 

215 Returns: 

216 list[VCFRecord]: A list of VCF records. 

217 """ 

218 

219 return _RustVCFParser.parse_file(str(file_path), limit)