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
« 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."""
16from __future__ import annotations
18from threading import RLock
19from typing import TYPE_CHECKING, Protocol, runtime_checkable
20from weakref import WeakValueDictionary
22from attrs import define, field, frozen
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
28if TYPE_CHECKING:
29 from ensembl.vep.sources.sequence_source import SequenceSource
31_CHROMOSOME_COORD_SYSTEM = CoordSystem(name="chromosome", level=CoordSystemLevel.CHROMOSOME, default=True)
34@frozen(kw_only=True, auto_attribs=True)
35class SliceKey:
36 """Identity of a cached slice."""
38 sequence_source_id: int | None
39 seq_region_name: str
40 start: int
41 end: int
42 strand: Strand
45@runtime_checkable
46class SliceCache(Protocol):
47 """Interface for caches that construct and share Slice objects."""
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."""
60 raise NotImplementedError
62 def clear(self) -> None:
63 """Clear cached state."""
65 raise NotImplementedError
68@define(kw_only=True, auto_attribs=True)
69class WeakSliceCache:
70 """Share slices without extending their lifetime.
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 """
76 _cache: WeakValueDictionary[SliceKey, Slice] = field(factory=WeakValueDictionary, init=False, repr=False)
77 _lock: RLock = field(factory=RLock, init=False, repr=False)
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.
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.
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.
102 Returns:
103 The shared Slice for the requested identity.
105 Raises:
106 ValueError: If the coordinates are invalid or the sequence-region length cannot be resolved.
107 """
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")
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 )
123 with self._lock:
124 cached = self._cache.get(key)
125 if cached is not None:
126 return cached
128 loaded = self._load_slice(
129 seq_region_name,
130 sequence_source,
131 start=start,
132 end=resolved_end,
133 strand=strand,
134 )
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
142 return loaded
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."""
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 )
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
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."""
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 )
184 def clear(self) -> None:
185 """Clear all live cache entries."""
187 with self._lock:
188 self._cache.clear()