Coverage for src/python/ensembl/vep/caches/codon_cache.py: 100%

97 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"""Cache codon and peptide edits shared across consequence annotations. 

15 

16Caches are instance-scoped and keyed by the complete codon-window edit. Key construction uses the 

17same mapping functions as the ``_codon_alleles`` fact so cache identity cannot drift from fact 

18evaluation. 

19""" 

20 

21from __future__ import annotations 

22 

23from collections import OrderedDict 

24from collections.abc import Callable 

25from threading import RLock 

26from typing import TYPE_CHECKING, NamedTuple, Protocol, TypeAlias, cast, runtime_checkable 

27 

28from attrs import define, field, frozen 

29 

30from ensembl.vep.annotators.consequence.facts.base import get_fact 

31from ensembl.vep.annotators.consequence.facts.helper import variant_genomic_span 

32from ensembl.vep.trace.events import FactOrigin 

33 

34if TYPE_CHECKING: 

35 from ensembl.vep.models.overlap import TranscriptVariationAllele 

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

37 

38__all__ = [ 

39 "CodonCache", 

40 "CodonEdit", 

41 "CodonEditKey", 

42 "CodonEditLRUCache", 

43 "CodonEditLoader", 

44] 

45 

46 

47class CodonEditKey(NamedTuple): 

48 """Identify one codon-window edit. 

49 

50 The key is deliberately over-inclusive: extra fields can reduce the hit rate, while omitted 

51 fields can reuse an incorrect consequence. A ``NamedTuple`` keeps hot-path construction and 

52 hashing inexpensive while retaining named fields. 

53 

54 Attributes: 

55 seq_region_name (str): Region the codon window sits on. 

56 codon_window_genomic_positions (tuple[int, ...]): Genomic positions of the whole codon(s). 

57 padding (int): Window bases with no genomic position -- the ``N`` before a CDS that starts 

58 part-way through a codon. Without it that first codon's key could equal a partial last 

59 codon's on another transcript over the same bases. 

60 strand (int): Reading direction, as ``Strand.value``. 

61 variant_min (int): Low genomic bound of the edit, fixing where in the window it falls. 

62 variant_max (int): High genomic bound of the edit. 

63 reference_allele (str): Reference bases. 

64 alternate_allele (str): Alternate bases. 

65 """ 

66 

67 seq_region_name: str 

68 codon_window_genomic_positions: tuple[int, ...] 

69 padding: int 

70 strand: int 

71 variant_min: int 

72 variant_max: int 

73 reference_allele: str 

74 alternate_allele: str 

75 

76 @classmethod 

77 def build(cls, fact_context: FactContext[TranscriptVariationAllele]) -> CodonEditKey | None: 

78 """Build a key for the codon window touched by a variant. 

79 

80 Args: 

81 fact_context (FactContext): Overlap being evaluated. Reads and memoises the 

82 ``_cds_footprint`` fact. 

83 

84 Returns: 

85 CodonEditKey | None: Cache key, or ``None`` if the variant touches no codon window. 

86 """ 

87 transcript = fact_context.overlap.feature 

88 footprint = cast("tuple[int, int] | None", get_fact(fact_context, "_cds_footprint")) 

89 mapper = transcript.cds_mapper 

90 if mapper is None: 

91 # No CDS mapper means no codon coordinates to key on. The caller's gate makes this 

92 # unreachable for a coding transcript, but the type allows it and an AttributeError 

93 # here would surface as a cache failure rather than a missing key. 

94 return None 

95 window = mapper.codon_window(footprint) 

96 if window is None: 

97 return None 

98 

99 accelerator = None 

100 annotator_context = fact_context.annotator_context 

101 if ( 

102 annotator_context is not None 

103 and annotator_context.mapper_index_cache is not None 

104 and transcript.cds_mapper is not None 

105 ): 

106 accelerator = annotator_context.mapper_index_cache.get_index( 

107 transcript, transcript.cds_mapper.build_index 

108 ) 

109 

110 window_start, window_end = window 

111 codon_window_genomic_positions = tuple( 

112 genomic_position 

113 for genomic_position in ( 

114 transcript.cds_offset_to_genomic(offset, accelerator=accelerator) 

115 for offset in range(window_start, window_end) 

116 ) 

117 if genomic_position is not None 

118 ) 

119 

120 variant = fact_context.overlap.overlapping_feature 

121 variant_min, variant_max = variant_genomic_span(fact_context) 

122 seq_region_name = transcript.slice.seq_region_name if transcript.slice is not None else "" 

123 reference_allele = variant.reference_allele or "" 

124 alternate_allele = variant.alternate_allele or "" 

125 return cls( 

126 seq_region_name, 

127 codon_window_genomic_positions, 

128 (window_end - window_start) - len(codon_window_genomic_positions), 

129 transcript.strand.value, 

130 variant_min, 

131 variant_max, 

132 reference_allele, 

133 alternate_allele, 

134 ) 

135 

136 

137CodonEditLoader: TypeAlias = Callable[[], "CodonEdit"] 

138 

139 

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

141class CodonEdit: 

142 """Store the mapping and sequence result for one codon-window edit. 

143 

144 Attributes: 

145 reference_codon (str): The reference codon window, transcript-sense. 

146 alternate_codon (str): ``reference_codon`` with the variant allele spliced in. 

147 reference_peptide (str): The amino acid translation of ``reference_codon``. 

148 alternate_peptide (str): The amino acid translation of ``alternate_codon``. 

149 """ 

150 

151 reference_codon: str 

152 alternate_codon: str 

153 reference_peptide: str 

154 alternate_peptide: str 

155 

156 

157@runtime_checkable 

158class CodonCache(Protocol): 

159 """Define storage used to reuse codon and peptide edits. 

160 

161 Implementations provide ``get_codon_edit`` and ``clear``. The default ``prefill`` method 

162 contains the storage-independent fact integration. 

163 """ 

164 

165 def get_codon_edit(self, key: CodonEditKey, loader: CodonEditLoader) -> CodonEdit: 

166 """Return the cached codon edit, loading it on a miss. 

167 

168 Args: 

169 key (CodonEditKey): Full-edit cache key. 

170 loader (CodonEditLoader): Loader used when ``key`` is not cached. 

171 

172 Returns: 

173 CodonEdit: Cached or newly loaded codon edit. 

174 """ 

175 raise NotImplementedError 

176 

177 def clear(self) -> None: 

178 """Clear cached state.""" 

179 raise NotImplementedError 

180 

181 def prefill(self, fact_context: FactContext[TranscriptVariationAllele]) -> None: 

182 """Prefill codon and peptide facts when the overlap is coding. 

183 

184 Run after zone-map prefill and before fact evaluation so cache hits avoid mapping and 

185 sequence work. Non-coding and non-exonic overlaps are ignored. 

186 

187 Args: 

188 fact_context (FactContext): Overlap to prefill. 

189 """ 

190 if fact_context.overlap.feature.translation is None: 

191 return 

192 if not get_fact(fact_context, "overlap_feature"): 

193 return 

194 if not get_fact(fact_context, "overlap_exon"): 

195 return 

196 

197 key = CodonEditKey.build(fact_context) 

198 if key is None: 

199 return 

200 

201 def _load_codon_edit() -> CodonEdit: 

202 reference_codon, alternate_codon = cast( 

203 "tuple[str, str]", get_fact(fact_context, "_codon_alleles") 

204 ) 

205 reference_peptide, alternate_peptide = cast( 

206 "tuple[str, str]", get_fact(fact_context, "_peptide_alleles") 

207 ) 

208 return CodonEdit( 

209 reference_codon=reference_codon, 

210 alternate_codon=alternate_codon, 

211 reference_peptide=reference_peptide, 

212 alternate_peptide=alternate_peptide, 

213 ) 

214 

215 codon_edit = self.get_codon_edit(key, _load_codon_edit) 

216 # On a hit, _load_codon_edit above never ran, so _codon_alleles/_peptide_alleles were never 

217 # computed (or charged) for this context -- this prefill is the entire mechanism, and the 

218 # only thing that makes either name known, correctly attributed to FactOrigin.CACHED. 

219 # On a miss, _load_codon_edit already populated the memo via get_fact; prefilling the same 

220 # values again here is redundant but harmless, and passing origin=CACHED never mislabels it, 

221 # because prefill only attributes the names it actually introduced to the memo. 

222 fact_context.prefill( 

223 { 

224 "_codon_alleles": (codon_edit.reference_codon, codon_edit.alternate_codon), 

225 "_peptide_alleles": (codon_edit.reference_peptide, codon_edit.alternate_peptide), 

226 }, 

227 origin=FactOrigin.CACHED, 

228 ) 

229 

230 

231@define(kw_only=True, auto_attribs=True, eq=False) 

232class CodonEditLRUCache(CodonCache): 

233 """Store codon edits in an instance-scoped LRU cache. 

234 

235 ``eq=False`` preserves identity semantics for mutable shared state. 

236 

237 Attributes: 

238 enabled (bool): Whether caching is enabled. 

239 max_entries (int): Maximum number of entries to retain. 

240 hit_count (int): Number of lookups served from the cache. 

241 miss_count (int): Number of lookups that invoked ``loader``. 

242 """ 

243 

244 enabled: bool = True 

245 max_entries: int = 65536 

246 hit_count: int = field(default=0, init=False) 

247 miss_count: int = field(default=0, init=False) 

248 _cache: OrderedDict[CodonEditKey, CodonEdit] = field(factory=OrderedDict, init=False, repr=False) 

249 _lock: RLock = field(factory=RLock, init=False, repr=False) 

250 

251 def get_codon_edit(self, key: CodonEditKey, loader: CodonEditLoader) -> CodonEdit: 

252 """Return the cached codon edit, loading and storing it on a miss. 

253 

254 Args: 

255 key (CodonEditKey): Full-edit cache key. 

256 loader (CodonEditLoader): Loader used when ``key`` is not cached. 

257 

258 Returns: 

259 CodonEdit: Cached or newly loaded codon edit. 

260 """ 

261 if not self.enabled: 

262 self.miss_count += 1 

263 return loader() 

264 

265 with self._lock: 

266 cached = self._cache.get(key) 

267 if cached is not None: 

268 self._cache.move_to_end(key) 

269 self.hit_count += 1 

270 return cached 

271 

272 codon_edit = loader() 

273 

274 with self._lock: 

275 self._cache[key] = codon_edit 

276 self._cache.move_to_end(key) 

277 self.miss_count += 1 

278 while len(self._cache) > self.max_entries: 

279 self._cache.popitem(last=False) 

280 

281 return codon_edit 

282 

283 def clear(self) -> None: 

284 """Clear the cache contents.""" 

285 with self._lock: 

286 self._cache.clear()