Coverage for src/python/ensembl/vep/runner/stats.py: 97%

67 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"""Annotated-file summaries and corpus fact profiles.""" 

15 

16from __future__ import annotations 

17 

18import logging 

19from typing import ClassVar 

20 

21from attrs import asdict 

22 

23from ensembl.vep.annotators.factory import build_annotator 

24from ensembl.vep.config import Config 

25from ensembl.vep.corpus.registry import CorpusOptionsError, build_corpus_from_options 

26from ensembl.vep.output.parser import parser_for 

27from ensembl.vep.runner.base import ExitCode 

28from ensembl.vep.runner.registry import register_runner 

29from ensembl.vep.stats import Reportable, RunSummaryCollector, render_reportable 

30from ensembl.vep.stats.profile import trace_run 

31 

32__all__ = ["Runner"] 

33 

34logger = logging.getLogger(__name__) 

35 

36 

37@register_runner("stats") 

38class Runner: 

39 """Runner for run summaries and corpus fact profiles. 

40 

41 ``run`` produces the summary as a by-product; this command re-reads one from what a run wrote 

42 (any tool's CSQ/ANN, not only ours), or -- with ``--profile`` -- turns tracing on over a corpus 

43 and reports what each fact cost. The profile is opt-in because it is measurably slower. 

44 

45 Attributes: 

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

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

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

49 """ 

50 

51 name: ClassVar[str] = "stats" 

52 sections: ClassVar[tuple[str, ...]] = ("logging", "source", "corpus", "annotation", "stats") 

53 description: ClassVar[str] = "summarise an annotated file, or profile the facts over a corpus" 

54 

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

56 """Hold the configuration.""" 

57 self.config = config 

58 

59 def run(self) -> ExitCode: 

60 """Build the requested report and write it.""" 

61 stats = self.config.stats 

62 input_file = self.config.source.input_file 

63 if stats.profile and input_file is not None: 

64 logger.error("--profile measures a generated corpus; give it or --input_file, not both") 

65 return ExitCode.USAGE 

66 if not stats.profile and input_file is None: 

67 logger.error("give --input_file to summarise an annotated file, or --profile to profile a corpus") 

68 return ExitCode.USAGE 

69 

70 try: 

71 report = self._profile() if stats.profile else self._summary() 

72 except CorpusOptionsError as problem: 

73 logger.error("%s", problem) 

74 return ExitCode.USAGE 

75 except (OSError, NotImplementedError, ValueError) as problem: 

76 logger.error("%s", problem) 

77 return ExitCode.FAILURE 

78 

79 self._emit(render_reportable(report, stats.output_format)) 

80 return ExitCode.OK 

81 

82 def _summary(self) -> Reportable: 

83 """Re-read the annotated input into a run summary.""" 

84 source = self.config.source 

85 assert source.input_file is not None 

86 reader = parser_for(source.input_file, source.format) 

87 collector = RunSummaryCollector( 

88 metadata={"input": str(source.input_file), "reader": type(reader).__name__} 

89 ) 

90 for variation in reader.parse(source.input_file): 

91 collector.observe(variation) 

92 summary = collector.finish() 

93 logger.info("summarised %s: %s", source.input_file, summary.subtitle) 

94 return summary 

95 

96 def _profile(self) -> Reportable: 

97 """Trace every overlap of the configured corpus and fold the derivations.""" 

98 annotation = self.config.annotation 

99 corpus = self.config.corpus 

100 built_corpus = build_corpus_from_options(corpus) 

101 annotator = build_annotator( 

102 **asdict(annotation), 

103 upstream_distance=self.config.source.upstream_distance, 

104 downstream_distance=self.config.source.downstream_distance, 

105 ) 

106 logger.info("profiling %s over %s", annotation.annotator, built_corpus.description) 

107 cost_table = "measured (fact_costs.json)" if annotation.fact_cost_override else "declared tiers" 

108 try: 

109 return trace_run( 

110 annotator, 

111 [overlap for _name, overlap in built_corpus.named_overlaps], 

112 annotator_name=annotation.annotator, 

113 cost_table=cost_table, 

114 ) 

115 finally: 

116 built_corpus.close() 

117 

118 def _emit(self, rendered: str) -> None: 

119 """Write the report to the configured destination.""" 

120 destination = self.config.stats.output_file 

121 if destination is None: 

122 print(rendered) 

123 return 

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

125 logger.info("wrote %s", destination)