Coverage for src/python/ensembl/vep/runner/bench/common.py: 81%

83 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"""Shared benchmark corpora, gates, and result handling.""" 

15 

16from __future__ import annotations 

17 

18import logging 

19from collections.abc import Iterator, Sequence 

20from contextlib import ExitStack, contextmanager 

21 

22from ensembl.vep.annotators.factory import build_annotator 

23from ensembl.vep.annotators.registry import available_annotators 

24from ensembl.vep.bench.baseline import ( 

25 BenchResults, 

26 RunInfo, 

27 compare_results, 

28 git_state, 

29 machine_info, 

30 utc_timestamp, 

31) 

32from ensembl.vep.bench.harness import ( 

33 REFERENCE_STRATEGY, 

34 TimingPolicy, 

35 conformance_gate, 

36 consequence_strategies, 

37) 

38from ensembl.vep.config import Config 

39from ensembl.vep.config.report import resolve_report_format 

40from ensembl.vep.corpus.registry import ( 

41 CorpusOptionsError, 

42 build_corpus, 

43 corpus_spec_from_options, 

44) 

45from ensembl.vep.corpus.spec import CorpusSpec 

46from ensembl.vep.models.overlap import TranscriptVariationAllele 

47from ensembl.vep.runner.base import ExitCode 

48 

49__all__ = [ 

50 "corpora", 

51 "gate", 

52 "policy", 

53 "record_results", 

54 "resolve_strategies", 

55 "run_info", 

56 "table_format", 

57] 

58 

59logger = logging.getLogger(__name__) 

60 

61 

62def resolve_strategies(requested: Sequence[str], default: Sequence[str]) -> list[str]: 

63 """Return the requested strategies, or the registered defaults when none were asked for. 

64 

65 Raises: 

66 ValueError: If a requested strategy is not registered. 

67 """ 

68 registered = set(available_annotators()) 

69 if not requested: 

70 return [name for name in default if name in registered] 

71 unknown = [name for name in requested if name not in registered] 

72 if unknown: 

73 raise ValueError(f"not registered: {', '.join(unknown)}") 

74 return list(requested) 

75 

76 

77def table_format(config: Config) -> str: 

78 """Return the table format the bench report asks for. 

79 

80 Raises: 

81 ValueError: If a diagram format was asked for; a timing table has no diagram form. 

82 """ 

83 

84 return resolve_report_format( 

85 config.bench.output_format, graph=False, table_default="text", graph_formats=() 

86 ) 

87 

88 

89@contextmanager 

90def corpora(config: Config) -> Iterator[list[tuple[str, list[TranscriptVariationAllele]]]]: 

91 """Keep each configured corpus alive while yielding its labelled overlaps.""" 

92 spec = corpus_spec_from_options(config.corpus) 

93 with ExitStack() as resources: 

94 try: 

95 labelled = [] 

96 for kind in spec.kinds: 

97 selected = CorpusSpec(kind=kind, parameters=spec.parameters) 

98 corpus = resources.enter_context(build_corpus(selected)) 

99 labelled.append((kind, [overlap for _name, overlap in corpus.named_overlaps])) 

100 except (KeyError, TypeError, ValueError, OSError) as error: 

101 if isinstance(error, CorpusOptionsError): 

102 raise 

103 message = error.args[0] if isinstance(error, KeyError) and error.args else str(error) 

104 raise CorpusOptionsError(str(message)) from error 

105 yield labelled 

106 

107 

108def policy(config: Config) -> TimingPolicy: 

109 """Return the configured timing policy.""" 

110 return TimingPolicy(repeats=config.bench.repeats, warmup=config.bench.warmup) 

111 

112 

113def gate(labelled: Sequence[tuple[str, Sequence[TranscriptVariationAllele]]]) -> bool: 

114 """Check every registered consequence strategy against the reference over every corpus, and log it.""" 

115 reference = build_annotator(annotator=REFERENCE_STRATEGY) 

116 candidates = { 

117 name: build_annotator(annotator=name) 

118 for name in consequence_strategies() 

119 if name != REFERENCE_STRATEGY 

120 } 

121 for label, overlaps in labelled: 

122 report = conformance_gate(overlaps, reference=reference, candidates=candidates) 

123 if not report.ok: 123 ↛ 124line 123 didn't jump to line 124 because the condition on line 123 was never true

124 suffix = "+" if report.truncated else "" 

125 logger.error( 

126 "conformance gate failed on %s (%d%s mismatches):", label, len(report.mismatches), suffix 

127 ) 

128 for mismatch in report.mismatches: 

129 logger.error(" %s", mismatch) 

130 return False 

131 logger.info( 

132 "conformance gate passed on %s: %d overlaps, %d strategies", 

133 label, 

134 report.overlaps, 

135 len(report.candidates), 

136 ) 

137 return True 

138 

139 

140def run_info(config: Config, verb: str) -> RunInfo: 

141 """Return what produced this run.""" 

142 spec = CorpusSpec.from_options(config.corpus) 

143 return RunInfo( 

144 verb=verb, 

145 corpus=spec.as_dict(), 

146 corpus_parameters=spec.parameter_hash(), 

147 git=git_state(), 

148 machine=machine_info(), 

149 timestamp=utc_timestamp(), 

150 repeats=config.bench.repeats, 

151 warmup=config.bench.warmup, 

152 ) 

153 

154 

155def record_results(config: Config, results: BenchResults) -> ExitCode: 

156 """Write the results if asked, and compare them against a baseline if one was given.""" 

157 bench = config.bench 

158 if bench.results_file is not None: 

159 results.write(bench.results_file) 

160 logger.info("wrote results to %s", bench.results_file) 

161 if bench.baseline_file is None: 

162 return ExitCode.OK 

163 if not bench.baseline_file.exists(): 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true

164 logger.error("baseline %s does not exist; write one first with --results_file", bench.baseline_file) 

165 return ExitCode.USAGE 

166 

167 comparison = compare_results( 

168 BenchResults.load(bench.baseline_file), results, threshold=bench.regression_threshold 

169 ) 

170 if comparison.corpus_changed: 

171 logger.error("the baseline was measured over a different corpus; the comparison would mean nothing") 

172 return ExitCode.USAGE 

173 for change in comparison.cost_changes: 173 ↛ 174line 173 didn't jump to line 174 because the loop on line 173 never started

174 logger.warning("cost changed -- a behaviour change, not a timing one: %s", change) 

175 for row in comparison.unmatched: 175 ↛ 176line 175 didn't jump to line 176 because the loop on line 175 never started

176 logger.warning("no baseline row for %s", row) 

177 for regression in comparison.regressions: 

178 logger.error("regression beyond %.0f%%: %s", bench.regression_threshold * 100, regression.line()) 

179 if comparison.ok: 

180 logger.info( 

181 "no regression beyond %.0f%% against %s", bench.regression_threshold * 100, bench.baseline_file 

182 ) 

183 return ExitCode.OK if comparison.ok else ExitCode.FAILURE