Coverage for src/python/ensembl/vep/caches/sequence_cache.py: 95%

63 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"""Sequence cache.""" 

15 

16from __future__ import annotations 

17 

18from collections import OrderedDict 

19from collections.abc import Callable 

20from threading import RLock 

21from typing import Protocol, TypeAlias, runtime_checkable 

22 

23from attrs import define, field 

24 

25SequenceSpanLoader: TypeAlias = Callable[[str, int, int], str | None] 

26 

27 

28# TBD: should this be an ABC instead of a Protocol? It would be more explicit, but less flexible. 

29@runtime_checkable 

30class SequenceCache(Protocol): 

31 """Interface for sequence caches.""" 

32 

33 def get_sequence( 

34 self, 

35 seq_region_name: str, 

36 start: int, 

37 end: int, 

38 loader: SequenceSpanLoader, 

39 ) -> str | None: 

40 """Return sequence for a span. 

41 

42 Args: 

43 seq_region_name (str): The sequence region name. 

44 start (int): 1-based inclusive start coordinate. 

45 end (int): 1-based inclusive end coordinate. 

46 loader (SequenceSpanLoader): Loader used when sequence is not cached. 

47 

48 Returns: 

49 str | None: The requested sequence, or None if unavailable. 

50 """ 

51 

52 raise NotImplementedError 

53 

54 def clear(self) -> None: 

55 """Clear cached state.""" 

56 

57 raise NotImplementedError 

58 

59 

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

61class SequenceBinnedLRUCache: 

62 """An in-memory LRU cache for fixed-size sequence chunks (or bins). 

63 

64 Attributes: 

65 enabled (bool): Whether the cache is enabled. Default is True. 

66 chunk_power (int): The power of two for the chunk size. Default is 18 (chunk size of 2^18 = 262,144). 

67 max_chunks (int): The maximum number of chunks to keep in the cache. Default is 1024. 

68 """ 

69 

70 enabled: bool = True 

71 chunk_power: int = 18 

72 max_chunks: int = 1024 

73 _cache: OrderedDict[tuple[str, int], str] = field(factory=OrderedDict, init=False, repr=False) 

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

75 

76 @property 

77 def chunk_size(self) -> int: 

78 """Return the cache chunk size.""" 

79 

80 return 1 << self.chunk_power 

81 

82 @property 

83 def max_span(self) -> int: 

84 """Return the largest sequence that can be stored in the cache.""" 

85 

86 return self.chunk_size * self.max_chunks 

87 

88 def chunk_start(self, position: int) -> int: 

89 """Return the start coordinate of the chunk containing the given position. 

90 

91 Position is 1-based inclusive. The returned chunk start is also 1-based inclusive. 

92 

93 Args: 

94 position (int): position of sequence in coordinate space. 

95 

96 Returns: 

97 int: chunk start coordinate. 

98 """ 

99 

100 return ((position - 1) >> self.chunk_power << self.chunk_power) + 1 

101 

102 def get_sequence( 

103 self, 

104 seq_region_name: str, 

105 start: int, 

106 end: int, 

107 loader: SequenceSpanLoader, 

108 ) -> str | None: 

109 """Return sequence for a span using binned chunk caching when useful. 

110 

111 Args: 

112 seq_region_name (str): The sequence region name. 

113 start (int): Start position of the sequence span. 

114 end (int): End position of the sequence span. 

115 loader (SequenceSpanLoader): Loader used when sequence is not cached. 

116 

117 Returns: 

118 str | None: The requested sequence, or None if unavailable. 

119 """ 

120 

121 requested_length = end - start + 1 

122 if not self.enabled or requested_length > self.max_span: 

123 return loader(seq_region_name, start, end) 

124 

125 chunk_start = self.chunk_start(start) 

126 sequence = "" 

127 

128 for current_start in range(chunk_start, end + 1, self.chunk_size): 

129 current_end = min(end, current_start + self.chunk_size - 1) 

130 chunk = self._get_or_load( 

131 (seq_region_name, current_start), 

132 lambda: self._load_chunk( 

133 seq_region_name, 

134 current_start, # pylint: disable=cell-var-from-loop 

135 loader, 

136 ), 

137 ) 

138 local_start = max(start, current_start) - current_start 

139 local_end = current_end - current_start + 1 

140 sequence += chunk[local_start:local_end] 

141 

142 return sequence 

143 

144 def _load_chunk( 

145 self, 

146 seq_region_name: str, 

147 chunk_start: int, 

148 loader: SequenceSpanLoader, 

149 ) -> str: 

150 """Load a full cached sequence chunk through the supplied span loader. 

151 

152 Args: 

153 seq_region_name (str): The sequence region name. 

154 chunk_start (int): Start coordinate of the chunk. 

155 loader (SequenceSpanLoader): Loader used to retrieve uncached sequence. 

156 

157 Returns: 

158 str: The loaded chunk sequence. 

159 """ 

160 

161 chunk_end = chunk_start + self.chunk_size - 1 

162 chunk = loader(seq_region_name, chunk_start, chunk_end) 

163 if chunk is None: 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true

164 return "N" * self.chunk_size 

165 

166 return chunk 

167 

168 def _get_or_load(self, key: tuple[str, int], loader: Callable[[], str]) -> str: 

169 """Return a cached chunk or populate it by calling loader. 

170 

171 Args: 

172 key (tuple[str, int]): Cache key made of sequence region name and chunk start. 

173 loader (Callable[[], str]): Loader used on cache miss. 

174 

175 Returns: 

176 str: The cached or newly loaded chunk. 

177 """ 

178 

179 if not self.enabled: 179 ↛ 180line 179 didn't jump to line 180 because the condition on line 179 was never true

180 return loader() 

181 

182 with self._lock: 

183 cached = self._cache.get(key) 

184 if cached is not None: 

185 self._cache.move_to_end(key) 

186 return cached 

187 

188 chunk = loader() 

189 

190 with self._lock: 

191 self._cache[key] = chunk 

192 self._cache.move_to_end(key) 

193 while len(self._cache) > self.max_chunks: 

194 self._cache.popitem(last=False) 

195 

196 return chunk 

197 

198 def clear(self) -> None: 

199 """Clear the cache contents.""" 

200 

201 with self._lock: 

202 self._cache.clear()