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

105 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"""Augmented interval-list feature indexing. 

15 

16``IntervalTree`` wraps ``ailist``, so interval intersection runs in C over the whole batch rather 

17than in Python per feature. ``FeatureIntervalTreeCache`` shares one tree per region and source, 

18the way ``zone_map.py`` pairs a structure with the cache that reuses it. ``Interval`` is the query 

19value the rest of the package builds, and keeps the insertion-point representation the matchers 

20depend on. 

21""" 

22 

23from __future__ import annotations 

24 

25import logging 

26from collections import OrderedDict 

27from threading import RLock 

28from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, runtime_checkable 

29 

30from ailist import AIList 

31from attrs import define, field, frozen 

32 

33if TYPE_CHECKING: 

34 # Both of these packages import ``caches``; keeping their imports out of runtime keeps that 

35 # one-way, so nothing that holds an interval has to be imported to build one. 

36 from ensembl.vep.matcher.base import IntervalLike 

37 from ensembl.vep.sources.feature_source import FeatureSource 

38 

39__all__ = [ 

40 "FeatureIntervalTreeCache", 

41 "Interval", 

42 "IntervalTree", 

43 "IntervalTreeCache", 

44 "IntervalTreeKey", 

45] 

46 

47logger = logging.getLogger(__name__) 

48 

49FeatureT = TypeVar("FeatureT", bound="IntervalLike") 

50"""The feature type an interval tree holds; anything with inclusive coordinates.""" 

51 

52 

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

54class Interval: 

55 """Inclusive genomic interval or interbase insertion point. 

56 

57 ``start=end+1`` denotes an insertion before ``start``. The interval index 

58 expands that point to its two flanking bases only for candidate retrieval. 

59 Matchers retain the zero-width insertion semantics. 

60 

61 Attributes: 

62 start (int): Inclusive start coordinate. 

63 end (int): Inclusive end coordinate, or ``start - 1`` for an insertion. 

64 """ 

65 

66 start: int 

67 end: int 

68 

69 def __attrs_post_init__(self) -> None: 

70 """Validate the interval representation.""" 

71 

72 if self.start < 1: 

73 raise ValueError("interval start must be at least 1") 

74 if self.end < self.start - 1: 

75 raise ValueError("interval end must not be less than start - 1") 

76 

77 @property 

78 def is_insertion(self) -> bool: 

79 """Return whether the interval is a zero-width insertion point.""" 

80 

81 return self.start == self.end + 1 

82 

83 @property 

84 def lookup_start(self) -> int: 

85 """Return the inclusive start used for candidate retrieval.""" 

86 

87 return max(1, self.end) if self.is_insertion else self.start 

88 

89 @property 

90 def lookup_end(self) -> int: 

91 """Return the inclusive end used for candidate retrieval.""" 

92 

93 return self.start if self.is_insertion else self.end 

94 

95 

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

97class IntervalTree(Generic[FeatureT]): 

98 """Feature index for overlap and proximity queries. 

99 

100 Attributes: 

101 features (list[FeatureT]): The indexed features, in the order they were added. 

102 """ 

103 

104 features: list[FeatureT] = field(factory=list) 

105 _intervals: AIList = field(factory=AIList, init=False, repr=False) 

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

107 

108 def __attrs_post_init__(self) -> None: 

109 """Index the features supplied at construction.""" 

110 

111 self._add_features_to_intervals(self.features, start_index=0) 

112 

113 def __getstate__(self) -> dict[str, Any]: 

114 """Return the tree's state without the lock, because the lock cannot be pickled.""" 

115 

116 return {"features": self.features, "_intervals": self._intervals} 

117 

118 def __setstate__(self, state: dict[str, Any]) -> None: 

119 """Restore the tree with a new lock of its own.""" 

120 

121 object.__setattr__(self, "features", state["features"]) 

122 object.__setattr__(self, "_intervals", state["_intervals"]) 

123 object.__setattr__(self, "_lock", RLock()) 

124 

125 def add_features(self, features: list[FeatureT]) -> None: 

126 """Add features to the index. 

127 

128 Args: 

129 features (list[FeatureT]): The features to add. 

130 """ 

131 

132 self._add_features_to_intervals(features, start_index=len(self.features)) 

133 self.features.extend(features) 

134 

135 def get_overlapping_features(self, start: int, end: int) -> list[FeatureT]: 

136 """Return every indexed feature overlapping an inclusive interval. 

137 

138 Args: 

139 start (int): The 1-based inclusive start coordinate. 

140 end (int): The inclusive end coordinate. 

141 

142 Returns: 

143 list[FeatureT]: The overlapping features, in the order they were added. 

144 

145 Raises: 

146 ValueError: If the start coordinate is not 1-based. 

147 """ 

148 

149 return [self.features[index] for index in self.get_overlapping_positions(start, end)] 

150 

151 def get_overlapping_features_by_feature(self, feature: IntervalLike) -> list[FeatureT]: 

152 """Return every indexed feature overlapping another feature's span. 

153 

154 Args: 

155 feature (IntervalLike): The feature whose span is queried. 

156 

157 Returns: 

158 list[FeatureT]: The overlapping features, in the order they were added. 

159 

160 Raises: 

161 ValueError: If the feature's coordinates are not 1-based. 

162 """ 

163 

164 return self.get_overlapping_features(start=feature.start, end=feature.end) 

165 

166 def get_overlapping_positions(self, start: int, end: int) -> list[int]: 

167 """Return the positions in ``features`` of every feature overlapping an interval. 

168 

169 A caller querying several intervals deduplicates and orders positions far more cheaply 

170 than the features themselves, which is why the positions are public. 

171 

172 Args: 

173 start (int): The 1-based inclusive start coordinate. 

174 end (int): The inclusive end coordinate. 

175 

176 Returns: 

177 list[int]: The matching positions, ascending. 

178 

179 Raises: 

180 ValueError: If the start coordinate is not 1-based. 

181 """ 

182 

183 with self._lock: 

184 start, end = self._check_interval(start, end) 

185 return sorted(int(index) for index in self._intervals.intersect_ids(start, end + 1)) 

186 

187 def get_nearest_features(self, start: int, end: int, k: int = 10) -> list[FeatureT]: 

188 """Return the ``k`` indexed features nearest an inclusive interval. 

189 

190 Args: 

191 start (int): The 1-based inclusive start coordinate. 

192 end (int): The inclusive end coordinate. 

193 k (int): How many features to return. 

194 

195 Returns: 

196 list[FeatureT]: The nearest features, nearest first. 

197 

198 Raises: 

199 ValueError: If the start coordinate is not 1-based. 

200 """ 

201 

202 with self._lock: 

203 start, end = self._check_interval(start, end) 

204 closest = self._intervals.closest(start, end + 1, k=k) 

205 return [self.features[index] for index in closest.ids] 

206 

207 def get_nearest_features_by_feature(self, feature: IntervalLike, k: int = 10) -> list[FeatureT]: 

208 """Return the ``k`` indexed features nearest another feature's span. 

209 

210 Args: 

211 feature (IntervalLike): The feature whose span is queried. 

212 k (int): How many features to return. 

213 

214 Returns: 

215 list[FeatureT]: The nearest features, nearest first. 

216 

217 Raises: 

218 ValueError: If the feature's coordinates are not 1-based. 

219 """ 

220 

221 return self.get_nearest_features(start=feature.start, end=feature.end, k=k) 

222 

223 def _add_features_to_intervals(self, features: list[FeatureT], start_index: int) -> None: 

224 """Index each feature under its own coordinates, skipping any that are invalid. 

225 

226 Args: 

227 features (list[FeatureT]): The features to index. 

228 start_index (int): The position the first feature is indexed under. 

229 """ 

230 

231 for offset, feature in enumerate(features): 

232 try: 

233 start, end = self._check_interval(feature.start, feature.end) 

234 except ValueError: 

235 logger.warning("Feature has invalid coordinates") 

236 continue 

237 self._intervals.add(start, end + 1, start_index + offset) 

238 

239 @staticmethod 

240 def _check_interval(start: int, end: int) -> tuple[int, int]: 

241 """Return the interval as an ordered 1-based pair. 

242 

243 Args: 

244 start (int): The 1-based start coordinate. 

245 end (int): The end coordinate. 

246 

247 Returns: 

248 tuple[int, int]: The start and end, swapped when given reversed. 

249 

250 Raises: 

251 ValueError: If the start coordinate is not 1-based. 

252 """ 

253 

254 if start < 1: 

255 raise ValueError("start must be 1-based: cannot be less than 1") 

256 if start > end: 

257 return end, start 

258 return start, end 

259 

260 

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

262class IntervalTreeKey: 

263 """Identity of one cached interval tree. 

264 

265 Attributes: 

266 seq_region_name (str): The sequence region the tree covers. 

267 start (int): The 1-based inclusive start of the covered span. 

268 end (int): The inclusive end of the covered span. 

269 source_id (int | None): Identity of the feature source the tree was filled from. 

270 """ 

271 

272 seq_region_name: str 

273 start: int 

274 end: int 

275 source_id: int | None 

276 

277 

278@runtime_checkable 

279class IntervalTreeCache(Protocol): 

280 """Region-based interval-tree cache.""" 

281 

282 def get_interval_tree( 

283 self, 

284 seq_region_name: str, 

285 start: int, 

286 end: int, 

287 source: FeatureSource, 

288 ) -> IntervalTree: 

289 """Return the interval tree for one region and source.""" 

290 

291 raise NotImplementedError 

292 

293 def clear(self) -> None: 

294 """Clear cached state.""" 

295 

296 raise NotImplementedError 

297 

298 

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

300class FeatureIntervalTreeCache: 

301 """Shared interval trees keyed by region and source. 

302 

303 Nothing is evicted yet; the cache is bounded by how many regions a run touches. 

304 """ 

305 

306 _cache: OrderedDict[IntervalTreeKey, IntervalTree] = field(factory=OrderedDict, init=False, repr=False) 

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

308 

309 def get_interval_tree( 

310 self, 

311 seq_region_name: str, 

312 start: int, 

313 end: int, 

314 source: FeatureSource, 

315 ) -> IntervalTree: 

316 """Return the interval tree for one region and source, building it on a miss. 

317 

318 Args: 

319 seq_region_name (str): The sequence region name. 

320 start (int): The 1-based inclusive start coordinate. 

321 end (int): The inclusive end coordinate. 

322 source (FeatureSource): The source whose features the tree holds. 

323 

324 Returns: 

325 IntervalTree: The cached or newly built tree. 

326 

327 Raises: 

328 ValueError: If the span is not a 1-based ordered interval. 

329 """ 

330 

331 if start < 1: 

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

333 if end < start: 

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

335 

336 key = IntervalTreeKey( 

337 seq_region_name=seq_region_name, 

338 start=start, 

339 end=end, 

340 source_id=id(source), 

341 ) 

342 with self._lock: 

343 cached = self._cache.get(key) 

344 if cached is not None: 

345 return cached 

346 tree: IntervalTree = IntervalTree() 

347 self._cache[key] = tree 

348 

349 return tree 

350 

351 def clear(self) -> None: 

352 """Clear every cached tree.""" 

353 

354 with self._lock: 

355 self._cache.clear()