Coverage for src/python/ensembl/vep/annotators/consequence/context/annotator.py: 94%

30 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"""Run-level state shared across overlap annotations. 

15 

16``FactContext`` belongs to one variant-feature overlap. ``AnnotatorContext`` spans the annotation 

17run and enables cross-overlap cache reuse. 

18""" 

19 

20from __future__ import annotations 

21 

22from typing import TYPE_CHECKING 

23 

24from attrs import define, field 

25 

26from ensembl.vep.common import DEFAULT_DISTANCE, Readthrough 

27 

28if TYPE_CHECKING: 

29 from ensembl.vep.models.overlap import TranscriptVariationAllele 

30 from ensembl.vep.annotators.consequence.context.fact import FactContext 

31 from ensembl.vep.annotators.consequence.rules.rulesets import FactRule 

32 from ensembl.vep.caches.codon_cache import CodonCache 

33 from ensembl.vep.caches.mapper_cache import MapperIndexCache 

34 from ensembl.vep.caches.zone_map import ZoneMapCache 

35 

36__all__ = ["AnnotatorContext"] 

37 

38 

39@define(kw_only=True, auto_attribs=True) 

40class AnnotatorContext: 

41 """Manage run-scoped caches shared across overlap annotations. 

42 

43 Attributes: 

44 zone_map_cache (ZoneMapCache | None): Per-transcript positional-fact zone maps or None to 

45 disables zone-map prefill. 

46 codon_cache (CodonCache | None): Shared-codon edit cache or None to disable codon reuse; the 

47 relevant codons are then computed per overlap. 

48 readthrough (Readthrough): How far translation may run past a destroyed stop codon, for 

49 the whole run. 

50 upstream_distance (int): Bases before a feature's 5' end that still count as upstream. 

51 downstream_distance (int): Bases past a feature's 3' end that still count as downstream. 

52 mapper_index_cache (MapperIndexCache | None): Byte-budget LRU of per-transcript 

53 genomic<->CDS offset accelerators. 

54 digest_candidate_cache (dict[str, tuple[FactRule, ...]]): Cheap-guard digest string -> 

55 the rules that survive it. Used by the annotators (e.g., linear) that build a guard digest per 

56 overlap. Always present -- it costs one dict and is never a 

57 correctness risk, since the key is a total function of the guard values. 

58 bitmask_candidate_cache (dict[int, tuple[FactRule, ...]]): Cheap-guard bitmask -> the 

59 rules that survive it. The same idea keyed by an int rather than a string, for the 

60 annotators that already compute guard flags as bits. 

61 cache_hits (int): Candidate-cache hits, summed across both candidate caches. 

62 cache_misses (int): Candidate-cache misses, summed across both candidate caches. 

63 """ 

64 

65 zone_map_cache: ZoneMapCache | None = field(default=None) 

66 codon_cache: CodonCache | None = field(default=None) 

67 readthrough: Readthrough = field(default=Readthrough.NONE) 

68 upstream_distance: int = field(default=DEFAULT_DISTANCE) 

69 downstream_distance: int = field(default=DEFAULT_DISTANCE) 

70 mapper_index_cache: MapperIndexCache | None = field(default=None) 

71 digest_candidate_cache: dict[str, tuple[FactRule, ...]] = field(factory=dict, init=False, repr=False) 

72 bitmask_candidate_cache: dict[int, tuple[FactRule, ...]] = field(factory=dict, init=False, repr=False) 

73 cache_hits: int = field(default=0, init=False) 

74 cache_misses: int = field(default=0, init=False) 

75 

76 def prepare( 

77 self, fact_context: FactContext[TranscriptVariationAllele], *, apply_zone_map: bool = True 

78 ) -> None: 

79 """Apply every enabled cache to one overlap, before its facts are computed. 

80 

81 The single place the caches' ordering is written down. Annotators call this once per overlap and 

82 are otherwise cache-agnostic. Turning a cache on or off is a change to the context a caller will 

83 make, not to the annotator. 

84 

85 Order is load-bearing and not arbitrary: 

86 

87 1. **Readthrough level first.** It changes what the sequence tier will compute, and 

88 assigning it invalidates the overlap's cached CDS alleles -- so it has to land before 

89 anything reads them, for the same reason the codon cache has to land before the 

90 sequence tier are evaluated. 

91 2. **Zone map second.** It prefills the positional tier, including ``overlap_feature`` and 

92 ``overlap_exon``, which is exactly what the codon cache's gate reads next, so running 

93 it first makes that gate free rather than evaluated. 

94 3. **Codon cache third, and still before any rule is evaluated.** Injecting once the 

95 sequence tier has already been reached is too late: the evaluation cost has been charged 

96 and the cache saves nothing. 

97 

98 Args: 

99 fact_context (FactContext): The overlap about to be evaluated. 

100 apply_zone_map (bool): False for a caller that will take the zone map's answers over a whole 

101 batch of overlaps instead (ZoneMapCache.columns), for example, a batch annotator (columnar). 

102 Doing both would compute every zone fact twice. 

103 """ 

104 # Stamp the run's readthrough level onto the overlap before anything reads its sequence. 

105 # Guarded because assigning invalidates the overlap's cached CDS/peptide alleles, and the 

106 # default-level case must stay a true no-op. 

107 transcript_overlap = fact_context.overlap 

108 if transcript_overlap.readthrough is not self.readthrough: 108 ↛ 109line 108 didn't jump to line 109 because the condition on line 108 was never true

109 transcript_overlap.readthrough = self.readthrough 

110 

111 # Both caches expose the same prefill(fact_context) shape, so applying them is symmetric; 

112 # each one's own gating and keying rules live with the cache rather than here. 

113 if apply_zone_map and self.zone_map_cache is not None: 

114 self.zone_map_cache.prefill(fact_context) 

115 if self.codon_cache is not None: 

116 self.codon_cache.prefill(fact_context) 

117 

118 def reset_candidate_caches(self) -> None: 

119 """Drop both candidate caches and their counters. 

120 

121 The candidate caches are keyed on cheap-guard values *for a particular rule set*, so a 

122 caller that swaps the rule set under a shared context must clear them or the second rule 

123 set will be served the first one's surviving rules. 

124 """ 

125 self.digest_candidate_cache.clear() 

126 self.bitmask_candidate_cache.clear() 

127 self.cache_hits = 0 

128 self.cache_misses = 0