Coverage for src/python/ensembl/vep/annotators/consequence/strategies/linear.py: 100%
62 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"""Evaluate consequence rules in rank order.
16For each overlap, the strategy computes cheap guard facts, uses their digest to cache candidate
17rules, evaluates candidates in rank order, and applies subsumption.
19This strategy is the conformance reference. Every other consequence strategy must produce the same
20ordered ``OverlapConsequence`` terms for the same input.
21"""
23from __future__ import annotations
25from collections.abc import Sequence
26import logging
27from typing import TYPE_CHECKING
29from attrs import field, frozen
31from ensembl.vep.annotators.consequence.strategies.base import ConsequenceAnnotator
32from ensembl.vep.annotators.registry import register_annotator
33from ensembl.vep.annotators.consequence.facts.base import get_fact
34from ensembl.vep.annotators.consequence.context.annotator import AnnotatorContext
35from ensembl.vep.annotators.consequence.context.fact import FactContext
36from ensembl.vep.annotators.consequence.rules.rulesets import FactRule, FactRuleSet, build_fact_ruleset, prune
37from ensembl.vep.trace import AnnotationTrace, TraceRecorder, describe_overlap
38from ensembl.vep.trace import reconstruct
39from ensembl.vep.models.overlap import FeatureOverlap, OverlapConsequence, TranscriptVariationAllele
41if TYPE_CHECKING:
42 from ensembl.vep.caches.codon_cache import CodonCache
43 from ensembl.vep.caches.zone_map import ZoneMapCache
45__all__ = ["LinearFactsAnnotator"]
47logger = logging.getLogger(__name__)
50@frozen(kw_only=True, auto_attribs=True)
51class _GuardDigestAlphabet:
52 """The sorted set of fact atoms that can be used as cheap guards.
54 Attributes:
55 atom_names (tuple[str, ...]): Every cheap guard atom name referenced by any rule in the
56 rule set this was built from, sorted for a stable digest string ordering.
57 """
59 atom_names: tuple[str, ...] = field(default=())
61 @classmethod
62 def build(cls, ruleset: FactRuleSet) -> _GuardDigestAlphabet:
63 """Collect every cheap guard atom referenced by any rule in a rule set.
65 Args:
66 ruleset (FactRuleSet): The rule set to inspect.
68 Returns:
69 _GuardDigestAlphabet: The sorted alphabet of cheap guard atom names.
70 """
71 atom_names = sorted({atom_name for rule in ruleset.rules for atom_name in rule.cheap_guard()})
72 return cls(atom_names=tuple(atom_names))
75@register_annotator("consequence.linear")
76class LinearFactsAnnotator(ConsequenceAnnotator[FactRuleSet]):
77 """Evaluate a fact rule set with a rank-ordered linear scan.
79 There is also a cheap guard to find shorter candidate rule lists, implemented by a digest-keyed
80 candidate cache.
82 Attributes:
83 name (str): Registry name, "consequence.linear".
84 ruleset (FactRuleSet): The compiled rule set this annotator evaluates.
85 """
87 name = "consequence.linear"
89 def __init__(
90 self,
91 ruleset: FactRuleSet | None = None,
92 annotator_context: AnnotatorContext | None = None,
93 *,
94 zone_map: ZoneMapCache | None = None,
95 codon_cache: CodonCache | None = None,
96 ) -> None:
97 """Initialize the annotator.
99 Args:
100 ruleset (FactRuleSet | None): The rule set to evaluate, or None to build the default
101 rule set from the checked-in consequence catalogue.
102 annotator_context (AnnotatorContext | None): Run-scoped caches to evaluate against,
103 or None (the default) for a fresh, private one.
104 zone_map (ZoneMapCache | None): Optional zone-map cache.
105 codon_cache (CodonCache | None): Optional shared-codon cache.
106 """
107 super().__init__(
108 ruleset if ruleset is not None else build_fact_ruleset(),
109 annotator_context,
110 zone_map=zone_map,
111 codon_cache=codon_cache,
112 )
113 self._guard_digest_alphabet: _GuardDigestAlphabet = _GuardDigestAlphabet.build(self.ruleset)
115 def _compute_guard_flags(self, fact_context: FactContext) -> dict[str, bool]:
116 """Compute the guard atom values in this annotator's guard digest alphabet.
118 Args:
119 fact_context (FactContext): The overlap to evaluate the guard atoms against.
121 Returns:
122 dict[str, bool]: Guard atom name -> boolean value.
123 """
124 return {
125 atom_name: bool(get_fact(fact_context, atom_name))
126 for atom_name in self._guard_digest_alphabet.atom_names
127 }
129 def _compute_digest(self, fact_context: FactContext) -> str:
130 """Compute digest string from the guard flags for an overlap.
132 Args:
133 fact_context (FactContext): The overlap to evaluate the guard atoms against.
135 Returns:
136 str: A digest string suitable as a candidate-rule-list cache key: identical for two
137 overlaps whenever every guard atom agrees between them.
138 """
139 return "".join(
140 f"{atom_name}{int(value)}" for atom_name, value in self._compute_guard_flags(fact_context).items()
141 )
143 def _candidates(self, fact_context: FactContext) -> tuple[FactRule, ...]:
144 """Returns the rules whose cheap guard holds for this overlap.
146 Args:
147 fact_context (FactContext): The context for the overlap being evaluated.
149 Returns:
150 tuple[FactRule, ...]: Every rule from self.ruleset whose cheap_guard() atoms are
151 all true for this overlap.
152 """
153 annotator_context = self.annotator_context
154 candidate_cache = annotator_context.digest_candidate_cache
155 digest = self._compute_digest(fact_context)
156 cached = candidate_cache.get(digest)
157 if cached is None:
158 annotator_context.cache_misses += 1
159 guard_flags = self._compute_guard_flags(fact_context)
160 cached = tuple(
161 rule
162 for rule in self.ruleset.rules
163 if all(guard_flags.get(atom) for atom in rule.cheap_guard())
164 )
165 candidate_cache[digest] = cached
166 else:
167 annotator_context.cache_hits += 1
168 return cached
170 def annotate_feature_overlap(self, overlap: FeatureOverlap) -> list[OverlapConsequence]:
171 """Calculate consequences for an overlap.
173 Args:
174 overlap (FeatureOverlap): The overlap to annotate.
176 Returns:
177 list[OverlapConsequence]: The consequences that apply, in rank order. Empty if
178 nothing matched.
180 Raises:
181 TypeError: If overlap is not a TranscriptVariationAllele (subclass of FeatureOverlap).
182 """
183 if not isinstance(overlap, TranscriptVariationAllele):
184 raise TypeError(
185 f"{type(self).__name__} only annotates TranscriptVariationAllele overlaps, got "
186 f"{type(overlap).__name__}"
187 )
189 recorder = TraceRecorder() if logger.isEnabledFor(logging.DEBUG) else None
190 fact_context = FactContext(
191 overlap=overlap, recorder=recorder, annotator_context=self.annotator_context
192 )
193 self.annotator_context.prepare(fact_context)
194 candidates = self._candidates(fact_context)
195 hit_terms = [rule.term for rule in candidates if rule.when.evaluate(fact_context)]
196 kept_terms = prune(self.ruleset, hit_terms, apply_default=False)
197 consequences = [self.ruleset.by_term[term].to_overlap_consequence() for term in kept_terms]
199 self.last_trace = None
200 if recorder is not None:
201 # Fact events first: recomputing the guard flags below goes back through get_fact, and
202 # those memo hits would otherwise be counted as reads the real path never made.
203 self.last_trace = AnnotationTrace(
204 fact_events=reconstruct.memo_fact_events(fact_context),
205 rule_events=reconstruct.guarded_rule_events(
206 self.ruleset.rules,
207 {rule.term for rule in candidates},
208 hit_terms,
209 self._compute_guard_flags(fact_context),
210 ),
211 prune_events=reconstruct.subsumption_events(self.ruleset.by_term, hit_terms),
212 emitted_terms=tuple(kept_terms),
213 annotator_name=self.name,
214 overlap_label=describe_overlap(overlap),
215 )
216 logger.debug(self.last_trace.format_explanation())
218 return consequences
220 def annotate_feature_overlaps(self, overlaps: Sequence[FeatureOverlap]) -> list[list[OverlapConsequence]]:
221 """Calculate consequences for a batch of overlaps, one at a time.
223 Args:
224 overlaps (Sequence[FeatureOverlap]): The overlaps to annotate, in order.
226 Returns:
227 list[list[OverlapConsequence]]: One consequence list per input overlap, same order.
228 """
229 return [self.annotate_feature_overlap(overlap) for overlap in overlaps]