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

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. 

15 

16For each overlap, the strategy computes cheap guard facts, uses their digest to cache candidate 

17rules, evaluates candidates in rank order, and applies subsumption. 

18 

19This strategy is the conformance reference. Every other consequence strategy must produce the same 

20ordered ``OverlapConsequence`` terms for the same input. 

21""" 

22 

23from __future__ import annotations 

24 

25from collections.abc import Sequence 

26import logging 

27from typing import TYPE_CHECKING 

28 

29from attrs import field, frozen 

30 

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 

40 

41if TYPE_CHECKING: 

42 from ensembl.vep.caches.codon_cache import CodonCache 

43 from ensembl.vep.caches.zone_map import ZoneMapCache 

44 

45__all__ = ["LinearFactsAnnotator"] 

46 

47logger = logging.getLogger(__name__) 

48 

49 

50@frozen(kw_only=True, auto_attribs=True) 

51class _GuardDigestAlphabet: 

52 """The sorted set of fact atoms that can be used as cheap guards. 

53 

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 """ 

58 

59 atom_names: tuple[str, ...] = field(default=()) 

60 

61 @classmethod 

62 def build(cls, ruleset: FactRuleSet) -> _GuardDigestAlphabet: 

63 """Collect every cheap guard atom referenced by any rule in a rule set. 

64 

65 Args: 

66 ruleset (FactRuleSet): The rule set to inspect. 

67 

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)) 

73 

74 

75@register_annotator("consequence.linear") 

76class LinearFactsAnnotator(ConsequenceAnnotator[FactRuleSet]): 

77 """Evaluate a fact rule set with a rank-ordered linear scan. 

78 

79 There is also a cheap guard to find shorter candidate rule lists, implemented by a digest-keyed 

80 candidate cache. 

81 

82 Attributes: 

83 name (str): Registry name, "consequence.linear". 

84 ruleset (FactRuleSet): The compiled rule set this annotator evaluates. 

85 """ 

86 

87 name = "consequence.linear" 

88 

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. 

98 

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) 

114 

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. 

117 

118 Args: 

119 fact_context (FactContext): The overlap to evaluate the guard atoms against. 

120 

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 } 

128 

129 def _compute_digest(self, fact_context: FactContext) -> str: 

130 """Compute digest string from the guard flags for an overlap. 

131 

132 Args: 

133 fact_context (FactContext): The overlap to evaluate the guard atoms against. 

134 

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 ) 

142 

143 def _candidates(self, fact_context: FactContext) -> tuple[FactRule, ...]: 

144 """Returns the rules whose cheap guard holds for this overlap. 

145 

146 Args: 

147 fact_context (FactContext): The context for the overlap being evaluated. 

148 

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 

169 

170 def annotate_feature_overlap(self, overlap: FeatureOverlap) -> list[OverlapConsequence]: 

171 """Calculate consequences for an overlap. 

172 

173 Args: 

174 overlap (FeatureOverlap): The overlap to annotate. 

175 

176 Returns: 

177 list[OverlapConsequence]: The consequences that apply, in rank order. Empty if 

178 nothing matched. 

179 

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 ) 

188 

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] 

198 

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()) 

217 

218 return consequences 

219 

220 def annotate_feature_overlaps(self, overlaps: Sequence[FeatureOverlap]) -> list[list[OverlapConsequence]]: 

221 """Calculate consequences for a batch of overlaps, one at a time. 

222 

223 Args: 

224 overlaps (Sequence[FeatureOverlap]): The overlaps to annotate, in order. 

225 

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]