Coverage for src/python/ensembl/vep/runner/explain.py: 91%

149 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"""End-to-end overlap consequence explanations.""" 

15 

16from __future__ import annotations 

17 

18import logging 

19from collections.abc import Sequence 

20from html import escape 

21from typing import ClassVar 

22 

23from ensembl.vep.annotators.consequence.graphs import derivation_graphs 

24from ensembl.vep.annotators.consequence.rules.catalogue import load_consequence_definitions 

25from ensembl.vep.config import Config 

26from ensembl.vep.config.report import resolve_report_format 

27from ensembl.vep.explain.annotate import NO_TRACE, annotate_with_trace 

28from ensembl.vep.explain.compare import diff_terms, diff_traces 

29from ensembl.vep.explain.selection import OverlapSelection 

30from ensembl.vep.explain.summary import format_summary, summary_html 

31from ensembl.vep.models.overlap import TranscriptVariationAllele 

32from ensembl.vep.render.graph import Graph, render_dot, render_mermaid, render_svg, tree 

33from ensembl.vep.render.page import Section, render_page 

34from ensembl.vep.runner.base import ExitCode 

35from ensembl.vep.runner.registry import register_runner 

36from ensembl.vep.trace import AnnotationTrace 

37 

38__all__ = ["Runner"] 

39 

40logger = logging.getLogger(__name__) 

41 

42GRAPH_EMITTERS = {"dot": render_dot, "mermaid": render_mermaid} 

43 

44 

45TERM_GROUPS = {"emitted": "Emitted", "pruned": "Pruned", "": "Not fired"} 

46TERM_GROUP_ORDER = {"emitted": 0, "pruned": 1, "": 2} 

47 

48 

49@register_runner("explain") 

50class Runner: 

51 """Runner for explaining one traced overlap annotation. 

52 

53 Attributes: 

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

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

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

57 """ 

58 

59 name: ClassVar[str] = "explain" 

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

61 description: ClassVar[str] = "explain one overlap's derivation, fact by fact and rule by rule" 

62 

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

64 """Hold the configuration and the selection it describes.""" 

65 self.config = config 

66 self._selection = OverlapSelection(config=config) 

67 

68 def run(self) -> ExitCode: 

69 """Select an overlap, annotate it with tracing on, and render the derivation. 

70 

71 Returns: 

72 ExitCode: OK once a derivation was rendered, or the code saying why not. 

73 """ 

74 try: 

75 return self._explain() 

76 except ValueError as unusable: 

77 # Building the sources needs transcripts to pair against, and a selector has to have a 

78 # shape. Both are the caller's mistake, so a usage error rather than a failure. 

79 logger.error("%s", unusable) 

80 return ExitCode.USAGE 

81 except LookupError as unknown: 

82 # Nothing matched the selectors, several did, or an index ran past the end. 

83 logger.error("%s", unknown) 

84 return ExitCode.USAGE 

85 except OSError as unreadable: 

86 # The sources read lazily, so an unreadable input surfaces here rather than at build 

87 # time. The readers raise instead of exiting, which leaves the exit code to this runner. 

88 logger.error("%s", unreadable) 

89 return ExitCode.USAGE 

90 finally: 

91 self._selection.close() 

92 

93 def _explain(self) -> ExitCode: 

94 """Render the derivation the options ask for. 

95 

96 Returns: 

97 ExitCode: OK once a derivation was rendered, or the code saying why not. 

98 

99 Raises: 

100 LookupError: If the selectors identify no overlap, or more than one. 

101 ValueError: If the configured sources or the selectors cannot be used. 

102 """ 

103 explain = self.config.explain 

104 # Resolved before anything is selected: an unrenderable request is wrong whatever matched. 

105 resolve_report_format(explain.output_format, graph=explain.graph, table_default="text") 

106 if explain.list_overlaps: 

107 self._emit(self._selection.listing()) 

108 return ExitCode.OK 

109 

110 if explain.name is None and explain.index is None and explain.variant is None: 

111 logger.error( 

112 "select an overlap with --name, --variant or --index; " 

113 "'vep corpus describe' or --list shows what is available" 

114 ) 

115 return ExitCode.USAGE 

116 

117 selected_name, overlap = self._selection.select() 

118 logger.info("explaining %s over %s", selected_name, overlap.feature.stable_id) 

119 if explain.compare: 

120 return self._compare(overlap) 

121 return self._explain_overlap(overlap) 

122 

123 def _explain_overlap(self, overlap: TranscriptVariationAllele) -> ExitCode: 

124 """Render one annotator's derivation of one overlap, after a summary of the overlap itself. 

125 

126 The graph source formats (dot, mermaid) are emitted bare, so that they still parse. 

127 """ 

128 annotator_name = self.config.annotation.annotator 

129 terms, trace = annotate_with_trace(self.config, annotator_name, overlap) 

130 if trace is None: 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true

131 logger.error("%s did not record a trace: %s", annotator_name, NO_TRACE) 

132 logger.info("emitted terms: %s", terms) 

133 return ExitCode.FAILURE 

134 

135 report_format = resolve_report_format( 

136 self.config.explain.output_format, graph=self.config.explain.graph, table_default="text" 

137 ) 

138 if report_format == "text": 

139 self._emit(f"{format_summary(overlap)}\n\n{trace.format_explanation()}") 

140 else: 

141 self._emit(self._graphs([(annotator_name, trace)], report_format, overlap)) 

142 return ExitCode.OK 

143 

144 def _compare(self, overlap: TranscriptVariationAllele) -> ExitCode: 

145 """Run two annotators over one overlap and report where their derivations part company. 

146 

147 A graph format draws the comparison rather than only describing it. The report still 

148 carries the verdict, so for the source formats -- which must stay parseable -- it is 

149 logged rather than printed. 

150 """ 

151 compare = self.config.explain.compare 

152 if len(compare) != 2: 

153 logger.error("--compare takes exactly two annotator names, given as NAME,NAME") 

154 return ExitCode.USAGE 

155 

156 name_a, name_b = compare 

157 terms_a, trace_a = annotate_with_trace(self.config, name_a, overlap) 

158 terms_b, trace_b = annotate_with_trace(self.config, name_b, overlap) 

159 

160 if trace_a is not None and trace_b is not None: 160 ↛ 162line 160 didn't jump to line 162 because the condition on line 160 was always true

161 report = diff_traces(trace_a, trace_b) 

162 elif trace_a is not None: 

163 logger.warning("%s recorded no trace: %s", name_b, NO_TRACE) 

164 report = diff_terms(trace_a, terms_b, name_b) 

165 elif trace_b is not None: 

166 logger.warning("%s recorded no trace: %s", name_a, NO_TRACE) 

167 report = diff_terms(trace_b, terms_a, name_a) 

168 else: 

169 logger.error("neither %s nor %s records a trace: %s", name_a, name_b, NO_TRACE) 

170 return ExitCode.FAILURE 

171 

172 report_format = resolve_report_format( 

173 self.config.explain.output_format, graph=self.config.explain.graph, table_default="text" 

174 ) 

175 if report_format == "text": 

176 self._emit(f"{format_summary(overlap)}\n\n{report}") 

177 else: 

178 traced = [ 

179 (name, trace) for name, trace in ((name_a, trace_a), (name_b, trace_b)) if trace is not None 

180 ] 

181 if report_format != "svg": 

182 logger.info("%s", report) 

183 self._emit(self._graphs(traced, report_format, overlap, report=report)) 

184 return ExitCode.OK if terms_a == terms_b else ExitCode.FAILURE 

185 

186 @staticmethod 

187 def _graphs( 

188 traces: Sequence[tuple[str, AnnotationTrace]], 

189 graph_format: str, 

190 overlap: TranscriptVariationAllele, 

191 report: str = "", 

192 ) -> str: 

193 """Render every term's result as source graphs or one navigable HTML document. 

194 

195 One annotator draws one set. Two draw one set when they produce the same drawing and the 

196 same terms -- a second identical copy says nothing -- and a set each when they do not, 

197 which is the divergence a comparison is asking about. Agreement is judged on the drawings 

198 rather than on the emitted terms: every annotator agrees on the terms by construction (the 

199 conformance suite proves it), while the strategies observe different facts to get there, 

200 and that difference is the whole subject of the picture. 

201 

202 Args: 

203 traces (Sequence[tuple[str, AnnotationTrace]]): Each annotator's name and derivation. 

204 graph_format (str): ``svg`` for the HTML document, else a graph source format. 

205 overlap (TranscriptVariationAllele): The overlap being explained. 

206 report (str): A comparison report to carry into the document, for ``svg``. 

207 

208 Returns: 

209 str: The rendering. 

210 """ 

211 drawn = [(name, derivation_graphs(trace), trace) for name, trace in traces] 

212 compared = tuple(name for name, _trace in traces) if len(traces) > 1 else () 

213 if ( 

214 len(drawn) == 2 

215 and drawn[0][1] == drawn[1][1] 

216 and drawn[0][2].emitted_terms == drawn[1][2].emitted_terms 

217 ): 

218 drawn = drawn[:1] 

219 

220 if graph_format == "svg": 

221 return Runner._graph_page(drawn, overlap, report=report, compared=compared) 

222 

223 emitter = GRAPH_EMITTERS[graph_format] 

224 return "\n\n".join(emitter(graph) for _name, graphs, _trace in drawn for graph in graphs) 

225 

226 @staticmethod 

227 def _graph_page( 

228 drawn: Sequence[tuple[str, tuple[Graph, ...], AnnotationTrace]], 

229 overlap: TranscriptVariationAllele, 

230 report: str = "", 

231 compared: Sequence[str] = (), 

232 ) -> str: 

233 """Return the overlap's summary, then every term proof in outcome order, from a side menu. 

234 

235 Two sets are kept apart in the menu, each group prefixed by its annotator, so the same 

236 term from each side is two entries rather than one anchor fighting over two drawings. 

237 

238 Args: 

239 drawn (Sequence[tuple[str, tuple[Graph, ...], AnnotationTrace]]): Each set's annotator 

240 name, graphs and derivation. One set, or one per annotator. 

241 overlap (TranscriptVariationAllele): The overlap being explained. 

242 report (str): A comparison report to show above the proofs, if any. 

243 compared (Sequence[str]): The annotators being compared, empty for a plain explanation. 

244 

245 Returns: 

246 str: The HTML document. 

247 """ 

248 definitions = load_consequence_definitions() 

249 ranks = {definition.term: definition.rank for definition in definitions} 

250 several = len(drawn) > 1 

251 entries: list[tuple[int, int, int, Section]] = [] 

252 

253 for position, (name, graphs, trace) in enumerate(drawn): 

254 

255 def section(term: str, blocks: tuple[str, ...], state: str, name: str = name) -> Section: 

256 """Return one term's menu entry, namespaced by annotator when there are two sets.""" 

257 return Section( 

258 identifier=f"{name}:{term}" if several else term, 

259 title=term, 

260 blocks=blocks, 

261 group=f"{name} · {TERM_GROUPS[state]}" if several else TERM_GROUPS[state], 

262 ) 

263 

264 for graph in graphs: 

265 state = graph.node(graph.title).state 

266 entries.append( 

267 ( 

268 position, 

269 TERM_GROUP_ORDER[state], 

270 ranks[graph.title], 

271 section(graph.title, (render_svg(graph, tree(graph)),), state), 

272 ) 

273 ) 

274 

275 drawn_terms = {graph.title for graph in graphs} 

276 for definition in definitions: 

277 if definition.term in drawn_terms: 

278 continue 

279 state = "emitted" if definition.term in trace.emitted_terms else "" 

280 explanation = ( 

281 "This fallback term was emitted because no expression term survived." 

282 if state == "emitted" 

283 else "This fallback term has no expression to fire for this overlap." 

284 ) 

285 entries.append( 

286 ( 

287 position, 

288 TERM_GROUP_ORDER[state], 

289 definition.rank, 

290 section(definition.term, (f"<p>{explanation}</p>",), state), 

291 ) 

292 ) 

293 

294 entries.sort(key=lambda entry: entry[:3]) 

295 sections = tuple(entry[3] for entry in entries) 

296 trace = drawn[0][2] 

297 nodes = "expression nodes: blue true, red false, white not observed" 

298 if compared and several: 

299 subtitle = ( 

300 f"{trace.overlap_label} · comparing {' vs '.join(compared)} · their derivations " 

301 f"differ, so each side's proofs are listed separately · {nodes}" 

302 ) 

303 elif compared: 

304 subtitle = ( 

305 f"{trace.overlap_label} · comparing {' vs '.join(compared)} · their derivations " 

306 f"are identical, so one set of proofs stands for both · {nodes}" 

307 ) 

308 else: 

309 counts = {group: 0 for group in TERM_GROUPS.values()} 

310 for section_entry in sections: 

311 counts[section_entry.group] += 1 

312 subtitle = ( 

313 f"{trace.overlap_label} · annotator: {trace.annotator_name} · " 

314 f"{counts['Emitted']} emitted · {counts['Pruned']} pruned · " 

315 f"{counts['Not fired']} not fired · {nodes}" 

316 ) 

317 

318 leading: list[Section] = [ 

319 Section(identifier="summary", title="Summary", blocks=(summary_html(overlap),)) 

320 ] 

321 if report: 

322 leading.append( 

323 Section( 

324 identifier="comparison", 

325 title="Comparison", 

326 blocks=(f"<pre>{escape(report)}</pre>",), 

327 ) 

328 ) 

329 return render_page("VEP consequence explanation", (*leading, *sections), subtitle=subtitle) 

330 

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

332 """Write a rendering to the configured destination.""" 

333 destination = self.config.explain.output_file 

334 if destination is None: 

335 print(rendered) 

336 return 

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

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