Coverage for src/python/ensembl/vep/bench/workspace.py: 88%

141 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"""The corpus on disk: written, indexed, annotated against, and removed again. 

15 

16An end-to-end benchmark needs what a real run needs -- a VCF, a bgzip-compressed and tabix-indexed 

17GFF3, and a FASTA with a ``.fai`` beside it -- because an unindexed source takes a different code 

18path, and timing that path would answer a different question. 

19 

20Everything this module writes is recorded as it is written, so ``clean()`` can remove exactly what 

21this invocation created and nothing else. A corpus already in the directory is reused and left 

22alone, which is what makes ``--corpus_dir`` safe to point at a corpus worth keeping. 

23""" 

24 

25from __future__ import annotations 

26 

27import logging 

28import shutil 

29import subprocess 

30from pathlib import Path 

31 

32from attrs import define, field 

33 

34from ensembl.vep.corpus.base import Corpus 

35from ensembl.vep.corpus.exporter import get_exporter 

36from ensembl.vep.corpus.exporter.formats.file.base import CORPUS_FILES 

37from ensembl.vep.corpus.exporter.formats.file.fasta import FASTA_NAME 

38from ensembl.vep.corpus.exporter.formats.file.gff3 import GFF3_NAME 

39from ensembl.vep.corpus.exporter.formats.file.vcf import VCF_NAME 

40 

41__all__ = ["INDEXING_TOOLS", "MissingTool", "Workspace"] 

42 

43logger = logging.getLogger(__name__) 

44 

45INDEXING_TOOLS = ("bgzip", "tabix") 

46"""The htslib executables the corpus has to be indexed with.""" 

47 

48GFF3_BGZ_NAME = "corpus.gff3.bgz" 

49"""The compressed, coordinate-sorted GFF3 the benchmark annotates against.""" 

50 

51_TABIX_INDEX_SUFFIX = ".tbi" 

52"""Suffix ``tabix -p gff`` writes beside the compressed GFF3.""" 

53 

54_FASTA_INDEX_SUFFIX = ".fai" 

55"""Suffix of the FASTA index the Rust reader needs for random access.""" 

56 

57 

58class MissingTool(RuntimeError): 

59 """An external executable the benchmark cannot run without is not on PATH.""" 

60 

61 

62def require_indexing_tools() -> None: 

63 """Check that every indexing executable is on PATH. 

64 

65 Raises: 

66 MissingTool: If any of them is missing, naming all of them at once so one install fixes it. 

67 """ 

68 missing = [name for name in INDEXING_TOOLS if shutil.which(name) is None] 

69 if missing: 

70 raise MissingTool( 

71 f"{', '.join(missing)} not found on PATH; the end-to-end benchmark annotates against an " 

72 "indexed corpus, so htslib is required (for example 'brew install htslib', or put an " 

73 "existing htslib bin directory on PATH)" 

74 ) 

75 

76 

77def fasta_index_lines(fasta_text: str) -> list[str]: 

78 """Return ``.fai`` records for a FASTA whose records are wrapped to a fixed width. 

79 

80 Written here rather than shelled out to ``samtools faidx``: the corpus writer controls the line 

81 width, so the offsets are arithmetic, and it keeps the tool requirement down to htslib. 

82 

83 Args: 

84 fasta_text (str): The FASTA file's complete text. 

85 

86 Returns: 

87 list[str]: One tab-separated ``name length offset linebases linewidth`` record per 

88 sequence, in file order. 

89 """ 

90 records: list[str] = [] 

91 name: str | None = None 

92 offset = 0 

93 length = 0 

94 linebases = 0 

95 linewidth = 0 

96 position = 0 

97 

98 for line in fasta_text.splitlines(keepends=True): 

99 if line.startswith(">"): 

100 if name is not None: 

101 records.append(f"{name}\t{length}\t{offset}\t{linebases}\t{linewidth}") 

102 name = line[1:].strip().split(maxsplit=1)[0] 

103 position += len(line) 

104 offset = position 

105 length = 0 

106 linebases = 0 

107 linewidth = 0 

108 continue 

109 position += len(line) 

110 if name is None: 

111 continue 

112 sequence = line.strip() 

113 if not linebases: 

114 linebases = len(sequence) 

115 linewidth = len(line) 

116 length += len(sequence) 

117 

118 if name is not None: 

119 records.append(f"{name}\t{length}\t{offset}\t{linebases}\t{linewidth}") 

120 return records 

121 

122 

123def sorted_gff3_text(gff3_text: str) -> str: 

124 """Return a GFF3 sorted the way tabix requires: headers first, then rows by region and start. 

125 

126 The corpus writes its rows one transcript at a time, which tabix rejects. The sort is stable, 

127 so rows sharing a start keep the order the corpus emitted them in -- and with it the order the 

128 CSQ entries come out in. 

129 

130 Args: 

131 gff3_text (str): The GFF3 file's complete text. 

132 

133 Returns: 

134 str: The same rows, sorted, with a trailing newline. 

135 """ 

136 headers: list[str] = [] 

137 rows: list[tuple[str, int, str]] = [] 

138 for line in gff3_text.splitlines(): 

139 if not line: 

140 continue 

141 if line.startswith("#"): 

142 headers.append(line) 

143 continue 

144 columns = line.split("\t") 

145 rows.append((columns[0], int(columns[3]), line)) 

146 

147 rows.sort(key=lambda row: (row[0], row[1])) 

148 return "\n".join(headers + [row[2] for row in rows]) + "\n" 

149 

150 

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

152class Workspace: 

153 """A directory holding the corpus, its indexes and the benchmark's own output files. 

154 

155 Attributes: 

156 directory (Path): Where everything lives. 

157 clean (bool): Remove what this invocation created when ``close`` is called. 

158 created (list[Path]): Files this invocation wrote, in creation order. 

159 created_directory (bool): Whether ``directory`` itself was created here. 

160 """ 

161 

162 directory: Path 

163 clean: bool = True 

164 created: list[Path] = field(factory=list, init=False) 

165 created_directory: bool = field(default=False, init=False) 

166 

167 @property 

168 def fasta_path(self) -> Path: 

169 """Return the corpus FASTA path.""" 

170 return self.directory / FASTA_NAME 

171 

172 @property 

173 def gff3_path(self) -> Path: 

174 """Return the uncompressed, unsorted corpus GFF3 path.""" 

175 return self.directory / GFF3_NAME 

176 

177 @property 

178 def indexed_gff3_path(self) -> Path: 

179 """Return the compressed, sorted, tabix-indexed GFF3 path.""" 

180 return self.directory / GFF3_BGZ_NAME 

181 

182 @property 

183 def vcf_path(self) -> Path: 

184 """Return the corpus VCF input path.""" 

185 return self.directory / VCF_NAME 

186 

187 def open(self) -> None: 

188 """Create the directory, remembering whether it had to be created.""" 

189 if not self.directory.exists(): 

190 self.created_directory = True 

191 self.directory.mkdir(parents=True, exist_ok=True) 

192 

193 def materialise(self, corpus: Corpus) -> None: 

194 """Write the corpus as files, or leave a corpus already in the directory alone. 

195 

196 Args: 

197 corpus (Corpus): The corpus to write. 

198 """ 

199 present = [name for name in CORPUS_FILES if (self.directory / name).exists()] 

200 if len(present) == len(CORPUS_FILES): 

201 logger.info("reusing the corpus already in %s", self.directory) 

202 return 

203 

204 manifest = get_exporter("file").export(corpus, self.directory, force=True) 

205 for name in CORPUS_FILES: 

206 self.track(self.directory / name) 

207 logger.info( 

208 "wrote the corpus to %s: %d transcripts, %d variants", 

209 self.directory, 

210 manifest.transcripts, 

211 manifest.variants, 

212 ) 

213 

214 def variant_count(self) -> int: 

215 """Return how many variant rows the corpus VCF holds.""" 

216 rows = 0 

217 with self.vcf_path.open(encoding="utf-8") as handle: 

218 for line in handle: 

219 if not line.startswith("#") and line.strip(): 

220 rows += 1 

221 return rows 

222 

223 def index(self) -> None: 

224 """Write the FASTA index, then the sorted, compressed and tabix-indexed GFF3. 

225 

226 Raises: 

227 MissingTool: If bgzip or tabix is not on PATH. 

228 subprocess.CalledProcessError: If either of them fails. 

229 """ 

230 require_indexing_tools() 

231 self._write_fasta_index() 

232 self._write_indexed_gff3() 

233 

234 def track(self, path: Path) -> None: 

235 """Record a path this invocation created, so ``close`` can remove it.""" 

236 if path not in self.created: 

237 self.created.append(path) 

238 

239 def close(self) -> None: 

240 """Remove what this invocation created, if cleaning was asked for.""" 

241 if not self.clean: 

242 logger.info("keeping %d file(s) in %s", len(self.created), self.directory) 

243 return 

244 

245 for path in reversed(self.created): 

246 path.unlink(missing_ok=True) 

247 if self.created_directory and self.directory.exists() and not any(self.directory.iterdir()): 

248 self.directory.rmdir() 

249 logger.info("removed %d file(s) from %s", len(self.created), self.directory) 

250 

251 def _write_fasta_index(self) -> None: 

252 """Write ``corpus.fa.fai`` beside the corpus FASTA.""" 

253 index_path = self.fasta_path.with_name(self.fasta_path.name + _FASTA_INDEX_SUFFIX) 

254 if index_path.exists(): 

255 return 

256 records = fasta_index_lines(self.fasta_path.read_text(encoding="utf-8")) 

257 index_path.write_text("\n".join(records) + "\n", encoding="utf-8") 

258 self.track(index_path) 

259 

260 def _write_indexed_gff3(self) -> None: 

261 """Compress the sorted GFF3 with bgzip and index it with tabix.""" 

262 index_path = self.indexed_gff3_path.with_name(self.indexed_gff3_path.name + _TABIX_INDEX_SUFFIX) 

263 if self.indexed_gff3_path.exists() and index_path.exists(): 

264 return 

265 

266 sorted_text = sorted_gff3_text(self.gff3_path.read_text(encoding="utf-8")) 

267 compressed = subprocess.run( 

268 ["bgzip", "-c"], 

269 input=sorted_text.encode("utf-8"), 

270 capture_output=True, 

271 check=True, 

272 ) 

273 self.indexed_gff3_path.write_bytes(compressed.stdout) 

274 self.track(self.indexed_gff3_path) 

275 

276 subprocess.run( 

277 ["tabix", "-p", "gff", "-f", str(self.indexed_gff3_path)], 

278 capture_output=True, 

279 check=True, 

280 ) 

281 self.track(index_path)