Coverage for src/python/ensembl/vep/annotators/consequence/context/fact.py: 100%

49 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"""Per-overlap fact evaluation and memoisation.""" 

15 

16from __future__ import annotations 

17 

18from collections.abc import Iterable, Mapping 

19from typing import TYPE_CHECKING, Generic, TypeVar 

20 

21from attrs import define, field 

22 

23from ensembl.vep.trace.events import FactOrigin, TraceRecorder 

24 

25if TYPE_CHECKING: 

26 from ensembl.vep.annotators.consequence.context.annotator import AnnotatorContext 

27 from ensembl.vep.models.genic import Transcript 

28 from ensembl.vep.models.overlap import FeatureOverlap, TranscriptVariationAllele 

29 from ensembl.vep.models.variation import VariationAllele 

30 

31__all__ = ["FactContext", "OverlapT_co"] 

32 

33OverlapT_co = TypeVar("OverlapT_co", bound="FeatureOverlap", covariant=True) 

34"""The kind of overlap a context carries. 

35 

36Covariance allows a ``FactContext[TranscriptVariationAllele]`` to be passed to a fact declared over 

37``FactContext[FeatureOverlap]``. 

38""" 

39 

40 

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

42class FactContext(Generic[OverlapT_co]): 

43 """Represent one variant-feature overlap during fact evaluation. 

44 

45 Wraps an overlap and stores its computed facts and other memoised values. 

46 

47 Attributes: 

48 overlap (OverlapT_co): The variant-feature overlap being annotated. Callers should not 

49 replace it because the type parameter is covariant. Runtime immutability is not 

50 enforced because ``attrs.setters.frozen`` adds substantial access cost. 

51 recorder (TraceRecorder | None): Opt-in trace gatherer, or None to disable tracing 

52 entirely. It collects only what a later reconstruction cannot recover -- read counts 

53 and which cache served which fact -- so the whole cost of tracing on this class is one 

54 ``is not None`` check per fact lookup. See ensembl.vep.trace. 

55 annotator_context (AnnotatorContext | None): The run-scoped state this overlap is being 

56 annotated under or None when the context is evaluated standalone (e.g., unit tests). 

57 """ 

58 

59 overlap: OverlapT_co 

60 recorder: TraceRecorder | None = field(default=None) 

61 annotator_context: AnnotatorContext | None = field(default=None) 

62 _memo: dict[str, object] = field(factory=dict, init=False, repr=False) 

63 _variant_span: tuple[int, int] | None = field(default=None, init=False, repr=False) 

64 _biotype: str | None = field(default=None, init=False, repr=False) 

65 

66 @property 

67 def memo(self) -> dict[str, object]: 

68 """Return the fact memo table. 

69 

70 Returns: 

71 dict[str, object]: The mutable memo table mapping fact name to computed value. 

72 """ 

73 return self._memo 

74 

75 @property 

76 def variant_span(self) -> tuple[int, int]: 

77 """Return the memoised genomic bounds of the variant. 

78 

79 An insertion is represented with ``end == start - 1``, so ``start`` alone is not reliably the 

80 lower bound, hence the min/max rather than a direct read. 

81 

82 Returns: 

83 tuple[int, int]: variant genomic (min, max) span. 

84 """ 

85 span = self._variant_span 

86 if span is None: 

87 variant = self.overlap.overlapping_feature 

88 span = (min(variant.start, variant.end), max(variant.start, variant.end)) 

89 self._variant_span = span 

90 return span 

91 

92 @property 

93 def biotype(self) -> str | None: 

94 """Return the memoised biotype of the overlapped feature. 

95 

96 If transcript/feature carries no ``biotype`` of its own in this model then falls back 

97 to gene. Resolved once per overlap 

98 

99 Returns: 

100 str | None: The biotype, or None if neither the feature nor its gene declares one. 

101 """ 

102 if self._biotype is None: 

103 feature = self.overlap.feature 

104 biotype = getattr(feature, "biotype", None) 

105 if biotype is None: 

106 gene = getattr(feature, "gene", None) 

107 if gene is not None: 

108 biotype = gene.biotype 

109 self._biotype = biotype 

110 return self._biotype 

111 

112 @classmethod 

113 def for_overlaps(cls, overlaps: Iterable[OverlapT_co]) -> list[FactContext[OverlapT_co]]: 

114 """Return one context per overlap. 

115 

116 What every caller that evaluates a whole corpus needs -- profiling, validation, benchmark 

117 gates -- rather than each rebuilding the same comprehension. 

118 """ 

119 return [cls(overlap=overlap) for overlap in overlaps] 

120 

121 def reset(self) -> None: 

122 """Clear the memo table and any other memoised state. 

123 

124 Lets the context be reused for a new overlap. 

125 """ 

126 self._memo.clear() 

127 self._variant_span = None 

128 self._biotype = None 

129 

130 def prefill(self, values: Mapping[str, object], *, origin: FactOrigin = FactOrigin.PREFILLED) -> None: 

131 """Seed the memo table with already-known values, without charging their cost. 

132 

133 Useful for an annotator that has derived some facts by cheaper means than calling their 

134 registered ``compute`` function, and wants later fact lookups to see those values as already memoised. 

135 

136 Args: 

137 values (Mapping[str, object]): Fact name -> value pairs to seed the memo table with. 

138 origin (FactOrigin): Which uncharged source these values came from, for example 

139 FactOrigin.PREFILLED for a zone map or FactOrigin.CACHED for the shared-codon 

140 cache. Ignored entirely when self.recorder is None. 

141 """ 

142 # Noted before the update, so only the names this call genuinely introduced are credited to 

143 # the cache. A codon-cache miss computes both facts through get_fact and then prefills the 

144 # same values back; those were computed, and the memo check is what keeps them so. 

145 if self.recorder is not None: 

146 self.recorder.note_served((name for name in values if name not in self._memo), origin) 

147 self._memo.update(values)