Coverage for src/python/ensembl/vep/caches/slice_cache.py: 97%

58 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"""Slice cache.""" 

15 

16from __future__ import annotations 

17 

18from threading import RLock 

19from typing import TYPE_CHECKING, Protocol, runtime_checkable 

20from weakref import WeakValueDictionary 

21 

22from attrs import define, field, frozen 

23 

24from ensembl.vep.common.enums import CoordSystemLevel, Strand 

25from ensembl.vep.models.sequence.coord_system import CoordSystem 

26from ensembl.vep.models.sequence.slice import Slice 

27 

28if TYPE_CHECKING: 

29 from ensembl.vep.sources.sequence_source import SequenceSource 

30 

31_CHROMOSOME_COORD_SYSTEM = CoordSystem(name="chromosome", level=CoordSystemLevel.CHROMOSOME, default=True) 

32 

33 

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

35class SliceKey: 

36 """Identity of a cached slice.""" 

37 

38 sequence_source_id: int | None 

39 seq_region_name: str 

40 start: int 

41 end: int 

42 strand: Strand 

43 

44 

45@runtime_checkable 

46class SliceCache(Protocol): 

47 """Interface for caches that construct and share Slice objects.""" 

48 

49 def get_slice( 

50 self, 

51 seq_region_name: str, 

52 sequence_source: SequenceSource | None = None, 

53 *, 

54 start: int = 1, 

55 end: int | None = None, 

56 strand: Strand = Strand.FORWARD, 

57 ) -> Slice: 

58 """Return the matching slice, constructing it on a cache miss.""" 

59 

60 raise NotImplementedError 

61 

62 def clear(self) -> None: 

63 """Clear cached state.""" 

64 

65 raise NotImplementedError 

66 

67 

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

69class WeakSliceCache: 

70 """Share slices without extending their lifetime. 

71 

72 Cached slices remain available while a feature or another consumer holds a strong reference. 

73 The cache entry is removed automatically after the last strong reference is released. 

74 """ 

75 

76 _cache: WeakValueDictionary[SliceKey, Slice] = field(factory=WeakValueDictionary, init=False, repr=False) 

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

78 

79 def get_slice( 

80 self, 

81 seq_region_name: str, 

82 sequence_source: SequenceSource | None = None, 

83 *, 

84 start: int = 1, 

85 end: int | None = None, 

86 strand: Strand = Strand.FORWARD, 

87 ) -> Slice: 

88 """Return the matching slice, constructing it on a cache miss. 

89 

90 If ``end`` is omitted, the complete sequence-region length is loaded from 

91 ``sequence_source``. A slice cannot be constructed when neither an explicit end nor a 

92 resolvable sequence-region length is available. 

93 

94 Args: 

95 seq_region_name: Name of the sequence region. 

96 sequence_source: Sequence provider used to resolve a missing end and attached to a 

97 newly built slice. 

98 start: 1-based inclusive slice start. 

99 end: 1-based inclusive slice end. Defaults to the complete sequence-region length. 

100 strand: Slice orientation relative to the sequence region. 

101 

102 Returns: 

103 The shared Slice for the requested identity. 

104 

105 Raises: 

106 ValueError: If the coordinates are invalid or the sequence-region length cannot be resolved. 

107 """ 

108 

109 resolved_end = self._resolve_end(seq_region_name, sequence_source, end) 

110 if start < 1: 

111 raise ValueError("slice start must be 1-based") 

112 if resolved_end < start: 

113 raise ValueError("slice start must be less than or equal to slice end") 

114 

115 key = SliceKey( 

116 sequence_source_id=id(sequence_source) if sequence_source is not None else None, 

117 seq_region_name=seq_region_name, 

118 start=start, 

119 end=resolved_end, 

120 strand=strand, 

121 ) 

122 

123 with self._lock: 

124 cached = self._cache.get(key) 

125 if cached is not None: 

126 return cached 

127 

128 loaded = self._load_slice( 

129 seq_region_name, 

130 sequence_source, 

131 start=start, 

132 end=resolved_end, 

133 strand=strand, 

134 ) 

135 

136 with self._lock: 

137 cached = self._cache.get(key) 

138 if cached is not None: 138 ↛ 139line 138 didn't jump to line 139 because the condition on line 138 was never true

139 return cached 

140 self._cache[key] = loaded 

141 

142 return loaded 

143 

144 @staticmethod 

145 def _resolve_end( 

146 seq_region_name: str, 

147 sequence_source: SequenceSource | None, 

148 end: int | None, 

149 ) -> int: 

150 """Resolve an explicit end or load the complete sequence-region length.""" 

151 

152 if end is not None: 

153 return end 

154 if sequence_source is None: 

155 raise ValueError( 

156 f"Cannot build slice for {seq_region_name}: no end or sequence source was provided" 

157 ) 

158 

159 seq_region_length = sequence_source.get_seq_region_length(seq_region_name) 

160 if seq_region_length is None: 

161 raise ValueError(f"Cannot build slice for {seq_region_name}: sequence-region length is unknown") 

162 return seq_region_length 

163 

164 @staticmethod 

165 def _load_slice( 

166 seq_region_name: str, 

167 sequence_source: SequenceSource | None, 

168 *, 

169 start: int, 

170 end: int, 

171 strand: Strand, 

172 ) -> Slice: 

173 """Construct a slice for a cache miss.""" 

174 

175 return Slice( 

176 coord_system=_CHROMOSOME_COORD_SYSTEM, 

177 seq_region_name=seq_region_name, 

178 start=start, 

179 end=end, 

180 strand=strand, 

181 sequence_source=sequence_source, 

182 ) 

183 

184 def clear(self) -> None: 

185 """Clear all live cache entries.""" 

186 

187 with self._lock: 

188 self._cache.clear()