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
« 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.
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"""
23from __future__ import annotations
25import logging
26from collections import OrderedDict
27from threading import RLock
28from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, runtime_checkable
30from ailist import AIList
31from attrs import define, field, frozen
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
39__all__ = [
40 "FeatureIntervalTreeCache",
41 "Interval",
42 "IntervalTree",
43 "IntervalTreeCache",
44 "IntervalTreeKey",
45]
47logger = logging.getLogger(__name__)
49FeatureT = TypeVar("FeatureT", bound="IntervalLike")
50"""The feature type an interval tree holds; anything with inclusive coordinates."""
53@frozen(kw_only=True, auto_attribs=True)
54class Interval:
55 """Inclusive genomic interval or interbase insertion point.
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.
61 Attributes:
62 start (int): Inclusive start coordinate.
63 end (int): Inclusive end coordinate, or ``start - 1`` for an insertion.
64 """
66 start: int
67 end: int
69 def __attrs_post_init__(self) -> None:
70 """Validate the interval representation."""
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")
77 @property
78 def is_insertion(self) -> bool:
79 """Return whether the interval is a zero-width insertion point."""
81 return self.start == self.end + 1
83 @property
84 def lookup_start(self) -> int:
85 """Return the inclusive start used for candidate retrieval."""
87 return max(1, self.end) if self.is_insertion else self.start
89 @property
90 def lookup_end(self) -> int:
91 """Return the inclusive end used for candidate retrieval."""
93 return self.start if self.is_insertion else self.end
96@define(kw_only=True, auto_attribs=True)
97class IntervalTree(Generic[FeatureT]):
98 """Feature index for overlap and proximity queries.
100 Attributes:
101 features (list[FeatureT]): The indexed features, in the order they were added.
102 """
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)
108 def __attrs_post_init__(self) -> None:
109 """Index the features supplied at construction."""
111 self._add_features_to_intervals(self.features, start_index=0)
113 def __getstate__(self) -> dict[str, Any]:
114 """Return the tree's state without the lock, because the lock cannot be pickled."""
116 return {"features": self.features, "_intervals": self._intervals}
118 def __setstate__(self, state: dict[str, Any]) -> None:
119 """Restore the tree with a new lock of its own."""
121 object.__setattr__(self, "features", state["features"])
122 object.__setattr__(self, "_intervals", state["_intervals"])
123 object.__setattr__(self, "_lock", RLock())
125 def add_features(self, features: list[FeatureT]) -> None:
126 """Add features to the index.
128 Args:
129 features (list[FeatureT]): The features to add.
130 """
132 self._add_features_to_intervals(features, start_index=len(self.features))
133 self.features.extend(features)
135 def get_overlapping_features(self, start: int, end: int) -> list[FeatureT]:
136 """Return every indexed feature overlapping an inclusive interval.
138 Args:
139 start (int): The 1-based inclusive start coordinate.
140 end (int): The inclusive end coordinate.
142 Returns:
143 list[FeatureT]: The overlapping features, in the order they were added.
145 Raises:
146 ValueError: If the start coordinate is not 1-based.
147 """
149 return [self.features[index] for index in self.get_overlapping_positions(start, end)]
151 def get_overlapping_features_by_feature(self, feature: IntervalLike) -> list[FeatureT]:
152 """Return every indexed feature overlapping another feature's span.
154 Args:
155 feature (IntervalLike): The feature whose span is queried.
157 Returns:
158 list[FeatureT]: The overlapping features, in the order they were added.
160 Raises:
161 ValueError: If the feature's coordinates are not 1-based.
162 """
164 return self.get_overlapping_features(start=feature.start, end=feature.end)
166 def get_overlapping_positions(self, start: int, end: int) -> list[int]:
167 """Return the positions in ``features`` of every feature overlapping an interval.
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.
172 Args:
173 start (int): The 1-based inclusive start coordinate.
174 end (int): The inclusive end coordinate.
176 Returns:
177 list[int]: The matching positions, ascending.
179 Raises:
180 ValueError: If the start coordinate is not 1-based.
181 """
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))
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.
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.
195 Returns:
196 list[FeatureT]: The nearest features, nearest first.
198 Raises:
199 ValueError: If the start coordinate is not 1-based.
200 """
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]
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.
210 Args:
211 feature (IntervalLike): The feature whose span is queried.
212 k (int): How many features to return.
214 Returns:
215 list[FeatureT]: The nearest features, nearest first.
217 Raises:
218 ValueError: If the feature's coordinates are not 1-based.
219 """
221 return self.get_nearest_features(start=feature.start, end=feature.end, k=k)
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.
226 Args:
227 features (list[FeatureT]): The features to index.
228 start_index (int): The position the first feature is indexed under.
229 """
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)
239 @staticmethod
240 def _check_interval(start: int, end: int) -> tuple[int, int]:
241 """Return the interval as an ordered 1-based pair.
243 Args:
244 start (int): The 1-based start coordinate.
245 end (int): The end coordinate.
247 Returns:
248 tuple[int, int]: The start and end, swapped when given reversed.
250 Raises:
251 ValueError: If the start coordinate is not 1-based.
252 """
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
261@frozen(kw_only=True, auto_attribs=True)
262class IntervalTreeKey:
263 """Identity of one cached interval tree.
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 """
272 seq_region_name: str
273 start: int
274 end: int
275 source_id: int | None
278@runtime_checkable
279class IntervalTreeCache(Protocol):
280 """Region-based interval-tree cache."""
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."""
291 raise NotImplementedError
293 def clear(self) -> None:
294 """Clear cached state."""
296 raise NotImplementedError
299@define(kw_only=True, auto_attribs=True)
300class FeatureIntervalTreeCache:
301 """Shared interval trees keyed by region and source.
303 Nothing is evicted yet; the cache is bounded by how many regions a run touches.
304 """
306 _cache: OrderedDict[IntervalTreeKey, IntervalTree] = field(factory=OrderedDict, init=False, repr=False)
307 _lock: RLock = field(factory=RLock, init=False, repr=False)
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.
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.
324 Returns:
325 IntervalTree: The cached or newly built tree.
327 Raises:
328 ValueError: If the span is not a 1-based ordered interval.
329 """
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")
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
349 return tree
351 def clear(self) -> None:
352 """Clear every cached tree."""
354 with self._lock:
355 self._cache.clear()