Coverage for src/python/ensembl/vep/trace/annotation.py: 99%
78 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« 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"""Completed annotation traces and text rendering.
16An ``AnnotationTrace`` is immutable and identifies both its overlap and annotator. Reconstruction
17builds it after annotation from the fact memo, rule results, and the small amount of live state in
18``TraceRecorder``. Optional event collections use empty tuples so consumers can iterate without
19special cases.
20"""
22from __future__ import annotations
24import logging
25from collections.abc import Iterator
26from contextlib import contextmanager
28from attrs import field, frozen
30from ensembl.vep.common import CostTier
31from ensembl.vep.common.constants import UNKNOWN_VALUE
32from ensembl.vep.trace.events import FactEvent, FactOrigin, PruneEvent, RuleEvent
34__all__ = [
35 "AnnotationTrace",
36 "annotation_tracing",
37 "describe_overlap",
38]
41@frozen(kw_only=True, auto_attribs=True)
42class AnnotationTrace:
43 """Record one overlap's derivation.
45 Attributes:
46 fact_events (tuple[FactEvent, ...]): Facts touched by the derivation, in materialisation
47 order, followed by facts proved false through ``requires`` propagation.
48 rule_events (tuple[RuleEvent, ...]): Every rule's verdict, in rank order.
49 prune_events (tuple[PruneEvent, ...]): Every subsumption decision.
50 emitted_terms (tuple[str, ...]): Terms remaining after subsumption.
51 annotator_name (str): Registered annotator name.
52 overlap_label (str): One-line description of the annotated overlap.
53 """
55 fact_events: tuple[FactEvent, ...] = field(default=())
56 rule_events: tuple[RuleEvent, ...] = field(default=())
57 prune_events: tuple[PruneEvent, ...] = field(default=())
58 emitted_terms: tuple[str, ...] = field(default=())
59 annotator_name: str = field(default="")
60 overlap_label: str = field(default="")
62 def events_by_origin(self, origin: FactOrigin) -> tuple[FactEvent, ...]:
63 """Return the fact events with one origin, in trace order."""
64 selected = []
65 for event in self.fact_events:
66 if event.origin is origin:
67 selected.append(event)
68 return tuple(selected)
70 @property
71 def computed_cost(self) -> int:
72 """Return the declared cost charged by this derivation."""
73 return sum(event.cost for event in self.fact_events if event.origin is FactOrigin.COMPUTED)
75 @property
76 def avoided_cost(self) -> int:
77 """Return the declared cost avoided through ``requires`` propagation."""
78 return sum(event.cost for event in self.fact_events if event.origin is FactOrigin.FORCED_FALSE)
80 def format_explanation(self) -> str:
81 """Return this trace as a human-readable derivation.
83 Returns:
84 str: Facts, rule verdicts, pruning decisions, and emitted terms.
85 """
86 lines = [f"{self.overlap_label} annotator: {self.annotator_name}"]
88 computed = self.events_by_origin(FactOrigin.COMPUTED)
89 prefilled = self.events_by_origin(FactOrigin.PREFILLED)
90 cached = self.events_by_origin(FactOrigin.CACHED)
91 forced_false = self.events_by_origin(FactOrigin.FORCED_FALSE)
92 reads = sum(event.reads for event in self.fact_events)
94 lines.append(
95 f" facts: {len(computed)} computed (cost {self.computed_cost}), {len(prefilled)} prefilled, "
96 f"{len(forced_false)} forced False (cost {self.avoided_cost} avoided), "
97 f"{len(cached)} cache hits, {reads} reads"
98 )
100 for event in self.fact_events:
101 origin_text = event.origin.value
102 if event.origin is FactOrigin.FORCED_FALSE and event.forced_by:
103 origin_text = f"forced False via {', '.join(event.forced_by)}"
104 cost_text = CostTier.label(event.cost) if event.origin is FactOrigin.COMPUTED else ""
105 read_text = f"x{event.reads}" if event.reads else ""
106 # A trailing space after every padded field (rather than relying on the padding alone)
107 # keeps columns visually separated even when a value overflows its nominal width -- a long
108 # fact name, or a tuple-valued fact's repr -- instead of the next column running into it.
109 lines.append(
110 f" {event.name:<26} {str(event.value):<10} {origin_text:<30} "
111 f"{cost_text:<9} {read_text}".rstrip()
112 )
114 lines.append(" rules:")
115 for rule_event in self.rule_events:
116 verdict = "FIRED" if rule_event.fired else "FALSE"
117 lines.append(f" [{rule_event.rank:>3}] {rule_event.term:<34} {verdict:<6} {rule_event.reason}")
119 if self.prune_events:
120 pruned_text = "; ".join(
121 f"{event.dropped_term} <- subsumed by {event.subsumed_by}" for event in self.prune_events
122 )
123 lines.append(f" pruned: {pruned_text}")
124 else:
125 lines.append(" pruned: (none)")
127 emitted_text = ", ".join(self.emitted_terms) if self.emitted_terms else "(none)"
128 lines.append(f" emitted: {emitted_text}")
130 return "\n".join(lines)
133class _SuppressAnnotatorDebugFilter(logging.Filter):
134 """Suppress annotator debug records when the caller renders traces."""
136 def filter(self, record: logging.LogRecord) -> bool:
137 """Return whether a record should be emitted."""
138 return not (record.levelno == logging.DEBUG and record.name.startswith("ensembl.vep.annotators"))
141@contextmanager
142def annotation_tracing(*, quiet: bool) -> Iterator[None]:
143 """Enable annotator tracing for the duration of a context.
145 Tracing uses the annotator logger level instead of adding a second flag to fact evaluation.
146 Quiet mode suppresses the annotator's debug rendering when the caller renders the same trace.
148 Args:
149 quiet (bool): Whether to suppress annotator debug records.
150 """
151 annotators_logger = logging.getLogger("ensembl.vep.annotators")
152 previous_level = annotators_logger.level
153 annotators_logger.setLevel(logging.DEBUG)
155 # The filter goes on the handlers, not the logger: a logger's filters apply only to records
156 # logged through that logger itself, never to its children's.
157 handlers = logging.getLogger("ensembl.vep").handlers
158 log_filter = _SuppressAnnotatorDebugFilter()
159 if quiet: 159 ↛ 162line 159 didn't jump to line 162 because the condition on line 159 was always true
160 for handler in handlers:
161 handler.addFilter(log_filter)
162 try:
163 yield
164 finally:
165 for handler in handlers:
166 handler.removeFilter(log_filter)
167 annotators_logger.setLevel(previous_level)
170def describe_overlap(overlap: object) -> str:
171 """Return a one-line label for a transcript and variant overlap.
173 The object is inspected without importing ``TranscriptVariationAllele`` so the trace event
174 layer remains independent of ``models``. The allele half is its ``display_name``, so a trace
175 header names the variant the way every other command names it.
177 Args:
178 overlap (object): Object exposing transcript and overlapping-allele attributes.
180 Returns:
181 str: Label containing the feature and the allele's name when available.
182 """
183 feature = getattr(overlap, "feature", None)
184 feature_label = getattr(feature, "stable_id", None) or repr(feature)
185 allele = getattr(overlap, "overlapping_feature", None)
186 return f"{feature_label} / {getattr(allele, 'display_name', None) or UNKNOWN_VALUE}"