Coverage for src/python/ensembl/vep/runner/run/default.py: 98%

140 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 default annotation runner. 

15 

16Annotating wires three things together and then gets out of the way: the input source reads 

17records, a ``PayloadIterator`` groups them, and an ``Executor`` runs each payload against an 

18``AnnotationBufferWorker``. Results come back in payload order whatever the worker count, and 

19only detached annotations cross back, which is what keeps a run's live model objects inside the 

20process that built them. 

21""" 

22 

23from __future__ import annotations 

24 

25import logging 

26import sys 

27from collections.abc import Iterator 

28from contextlib import nullcontext 

29from functools import cached_property, partial 

30from pathlib import Path 

31from typing import ClassVar 

32 

33from ensembl.vep.config import Config 

34from ensembl.vep.output.factory import AnnotatedVariant, AnnotatedVariants 

35from ensembl.vep.output.factory.write import available_output_writers, get_output_writer 

36from ensembl.vep.runner.base import ExitCode 

37from ensembl.vep.runner.registry import register_runner 

38from ensembl.vep.runner.run.output_transaction import OutputTransaction 

39from ensembl.vep.runner.run.progress import VariantProgress 

40from ensembl.vep.sources.build import ( 

41 InputSource, 

42 build_chromosome_synonyms, 

43 build_input_source, 

44 detect_input_format, 

45) 

46from ensembl.vep.stats import RunSummaryCollector, render_reportable 

47from ensembl.vep.workflow.build import workflow_for_command 

48from ensembl.vep.workflow.executor import ExecutionSpec, Executor, PayloadIterator 

49from ensembl.vep.workflow.worker import AnnotationBufferResult, AnnotationBufferWorker 

50 

51__all__ = ["Runner"] 

52 

53logger = logging.getLogger(__name__) 

54 

55_SUMMARY_SUFFIXES = {"html": ".html", "text": ".txt", "json": ".json"} 

56 

57 

58@register_runner("run.default", default_for_group=True) 

59class Runner: 

60 """Runner for annotating an input file. 

61 

62 Attributes: 

63 name (ClassVar[str]): The registry name. 

64 sections (ClassVar[tuple[str, ...]]): The configuration sections read. 

65 description (ClassVar[str]): One-line description for the subcommand list. 

66 """ 

67 

68 name: ClassVar[str] = "run.default" 

69 sections: ClassVar[tuple[str, ...]] = ( 

70 "logging", 

71 "source", 

72 "annotation", 

73 "execution", 

74 "run", 

75 ) 

76 description: ClassVar[str] = "annotate variants against a set of annotation sources" 

77 

78 def __init__(self, config: Config) -> None: 

79 """Initialize the runner.""" 

80 self.config = config 

81 

82 @cached_property 

83 def input_source(self) -> InputSource: 

84 """Return the source this process reads input records with, built once. 

85 

86 The parent only reads: it streams records, counts them, and passes the input's own header 

87 through. Every model is built in the worker that annotates it, so this source is given no 

88 reference sequence -- reading records needs none. 

89 

90 Built on first use rather than in ``__init__`` because a runner is constructed before 

91 anything has validated what it was given: a configuration naming no input file has to be 

92 reported by ``run()``, which turns it into a usage error, rather than raise while the 

93 runner is being built. 

94 

95 Returns: 

96 InputSource: The input source the configured format reads with. 

97 

98 Raises: 

99 ValueError: If no input file is configured. 

100 """ 

101 source_config = self.config.source 

102 if source_config.input_file is None: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true

103 raise ValueError("give --input_file to annotate") 

104 return build_input_source( 

105 source_config, 

106 sequence_source=None, 

107 synonyms=build_chromosome_synonyms(source_config), 

108 ) 

109 

110 def run(self) -> ExitCode: 

111 """Annotate the input and write its output and optional summary.""" 

112 destination = self.config.run.output_file 

113 summary_destination = self._summary_destination() 

114 

115 try: 

116 self._validate_run(destination, summary_destination) 

117 if destination is None: 

118 self._run_to_stdout(summary_destination) 

119 else: 

120 self._run_to_file(destination, summary_destination) 

121 except (OSError, ValueError) as error: 

122 logger.error("%s", error) 

123 return ExitCode.USAGE 

124 

125 return ExitCode.OK 

126 

127 def annotate(self, *, show_progress: bool = False) -> AnnotatedVariants: 

128 """Return a closable stream of annotated variants in input order. 

129 

130 Args: 

131 show_progress (bool): Show interactive progress when configuration and stderr allow it. 

132 

133 Returns: 

134 AnnotatedVariants: The ordered stream and the summary collector it fills. 

135 

136 Raises: 

137 ValueError: If no input file is configured. 

138 """ 

139 input_file = self.config.source.input_file 

140 if input_file is None: 

141 raise ValueError("give --input_file to annotate") 

142 

143 specification = ExecutionSpec.from_config(self.config.execution) 

144 executor: Executor[tuple[str, ...], AnnotationBufferResult] = Executor( 

145 specification=specification, 

146 worker_factory=partial(AnnotationBufferWorker, self.config), 

147 payload_iterator=PayloadIterator( 

148 records=self.input_source.iter_all_records(), 

149 batch_size=specification.buffer_size, 

150 region_of=self.input_source.region_of, 

151 ), 

152 ) 

153 collector = RunSummaryCollector( 

154 metadata={ 

155 "input": str(input_file), 

156 "annotator": self.config.annotation.annotator, 

157 } 

158 ) 

159 variants = self._iter_annotated_variants( 

160 executor.execute(), 

161 collector=collector, 

162 show_progress=self._progress_wanted(show_progress), 

163 ) 

164 return AnnotatedVariants(variants=variants, collector=collector) 

165 

166 def _progress_wanted(self, show_progress: bool) -> bool: 

167 """Return whether interactive progress was asked for and is worth rendering.""" 

168 return ( 

169 show_progress 

170 and not self.config.run.no_progress 

171 and not self.config.logging.quiet 

172 and sys.stderr.isatty() 

173 ) 

174 

175 def _validate_run( 

176 self, 

177 destination: Path | None, 

178 summary_destination: Path | None, 

179 ) -> None: 

180 """Validate source, format, and every destination before doing work.""" 

181 source_config = self.config.source 

182 run_config = self.config.run 

183 # Before any worker starts, so an unimplemented command is reported once here rather than 

184 # by every worker process once it has opened its sources. 

185 workflow_for_command(self.config.command) 

186 if source_config.input_file is None: 

187 raise ValueError("give --input_file to annotate; 'vep corpus describe' explores a corpus instead") 

188 # Resolved here as well, so an input format with no reader is reported once before any 

189 # worker starts rather than by every worker that opens the input. 

190 detect_input_format(source_config.input_file, source_config.format) 

191 available_formats = available_output_writers() 

192 if run_config.output_format not in available_formats: 

193 supported_formats = ", ".join(available_formats) 

194 raise ValueError( 

195 f"no writer for {run_config.output_format!r} yet; supported: {supported_formats}" 

196 ) 

197 if destination is not None and destination.is_dir(): 

198 # Reached by --output_file . , which is a mistake rather than a request to stream. 

199 raise ValueError(f"{destination} is a directory; give a file to write, or STDOUT to stream") 

200 if destination is not None and summary_destination == destination: 

201 raise ValueError("stats_file must differ from output_file") 

202 if run_config.force_overwrite: 

203 return 

204 for planned_destination in (destination, summary_destination): 

205 if planned_destination is not None and planned_destination.exists(): 

206 raise ValueError(f"{planned_destination} exists; pass --force_overwrite to replace it") 

207 

208 def _run_to_stdout(self, summary_destination: Path | None) -> None: 

209 """Stream annotations to stdout and write or log their summary.""" 

210 _variant_count, collector = self._run_buffered(None) 

211 if not self.config.run.no_stats: 211 ↛ exitline 211 didn't return from function '_run_to_stdout' because the condition on line 211 was always true

212 self._write_collector_summary(collector, summary_destination) 

213 if summary_destination is not None: 

214 logger.info("wrote %s", summary_destination) 

215 

216 def _run_to_file(self, destination: Path, summary_destination: Path | None) -> None: 

217 """Commit annotation and summary files after both render successfully.""" 

218 transaction = OutputTransaction(replace_existing=self.config.run.force_overwrite) 

219 try: 

220 temporary_output = transaction.stage(destination) 

221 variant_count, collector = self._run_buffered(temporary_output) 

222 if summary_destination is not None: 

223 temporary_summary = transaction.stage(summary_destination) 

224 self._write_collector_summary(collector, temporary_summary) 

225 transaction.commit() 

226 finally: 

227 transaction.cleanup() 

228 

229 logger.info("wrote %s (%d variants)", destination, variant_count) 

230 if summary_destination is not None: 

231 logger.info("wrote %s", summary_destination) 

232 

233 def _run_buffered(self, destination: Path | None) -> tuple[int, RunSummaryCollector]: 

234 """Consume the Python annotation stream through the selected writer.""" 

235 input_file = self.config.source.input_file 

236 assert input_file is not None 

237 writer = get_output_writer( 

238 self.config.run.output_format, 

239 command_line=f"vep run --input_file {input_file}", 

240 ) 

241 output = nullcontext(sys.stdout) if destination is None else destination.open("w", encoding="utf-8") 

242 annotations = self.annotate(show_progress=True) 

243 with output as handle: 

244 with annotations: 

245 for header in writer.headers(self.input_source.header_lines()): 

246 handle.write(f"{header}\n") 

247 for variant in annotations: 

248 handle.write(f"{writer.line(variant)}\n") 

249 return annotations.variant_count, annotations.collector 

250 

251 def _write_collector_summary( 

252 self, 

253 collector: RunSummaryCollector, 

254 destination: Path | None, 

255 ) -> None: 

256 """Write a streamed summary assembled from worker deltas.""" 

257 summary = collector.finish() 

258 if destination is None: 

259 logger.info("run summary: %s", summary.subtitle) 

260 return 

261 rendered = render_reportable(summary, self.config.run.stats_format) 

262 destination.write_text(rendered, encoding="utf-8") 

263 

264 def _iter_annotated_variants( 

265 self, 

266 results: Iterator[AnnotationBufferResult], 

267 *, 

268 collector: RunSummaryCollector, 

269 show_progress: bool, 

270 ) -> Iterator[AnnotatedVariant]: 

271 """Merge worker summaries while yielding each detached variant. 

272 

273 Args: 

274 results (Iterator[AnnotationBufferResult]): What the executor yields, in input order. 

275 collector (RunSummaryCollector): The run summary each result's delta is merged into. 

276 show_progress (bool): Whether to draw the interactive progress line. 

277 

278 Yields: 

279 Iterator[AnnotatedVariant]: Each annotated variant, in input order. 

280 """ 

281 # `record_count` should be never be called with `scan=True`: if the input does not declare a count 

282 # it would cost a whole extra pass over it, which is not worth it for progress reporting. 

283 # Without a count, one the bar is drawn unsized. 

284 variant_total = self.input_source.record_count() if show_progress else None 

285 try: 

286 with VariantProgress(total=variant_total, enabled=show_progress) as progress: 

287 for result in results: 

288 collector.merge_ordered_delta(result.summary_delta) 

289 for variant in result.variants: 

290 yield variant 

291 progress.advance(1) 

292 finally: 

293 close = getattr(results, "close", None) 

294 if close is not None: 294 ↛ exitline 294 didn't return from function '_iter_annotated_variants' because the condition on line 294 was always true

295 close() 

296 

297 def _summary_destination(self) -> Path | None: 

298 """Return the explicitly named or output-derived summary destination.""" 

299 if self.config.run.no_stats: 

300 return None 

301 return self.config.run.stats_file or self._derived_summary_path() 

302 

303 def _derived_summary_path(self) -> Path | None: 

304 """Return the summary path derived from output, or ``None`` for stdout.""" 

305 output_file = self.config.run.output_file 

306 if output_file is None: 

307 return None 

308 suffix = _SUMMARY_SUFFIXES.get(self.config.run.stats_format, ".txt") 

309 return output_file.with_name(f"{output_file.name}_summary{suffix}")