Coverage for src/python/ensembl/vep/sources/sequence_source.py: 96%
54 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"""Abstract base for sequence sources."""
16from __future__ import annotations
18from abc import ABC, abstractmethod
19from threading import RLock
21from attrs import define, field
23from ensembl.vep.caches import SequenceCache
24from ensembl.vep.common import Strand, reverse_complement
27@define(kw_only=True, auto_attribs=True)
28class SequenceSource(ABC):
29 """Unified interface for sources that provide sequence for slices."""
31 cache: SequenceCache | None = field(default=None)
32 _seq_region_lengths: dict[str, int] = field(factory=dict, init=False, repr=False)
33 _lock: RLock = field(factory=RLock, init=False, repr=False)
35 @property
36 def sequence_region_names(self) -> frozenset[str]:
37 """Return the sequence-region names this source declares.
39 These are the reference spelling of a run: every model slice is built in it, and this
40 source is asked for sequence by it. A source that can list its regions up front -- a
41 FASTA's index, a table of them -- overrides this; the rest declare none, which leaves
42 every uploaded name resolving to itself.
44 Returns:
45 frozenset[str]: The declared names, empty when the source lists none.
46 """
48 return frozenset()
50 def get_seq_region_length(self, seq_region_name: str) -> int | None:
51 """Return the length of a sequence region, caching when available.
53 Args:
54 seq_region_name (str): The sequence region name.
56 Returns:
57 int | None: The sequence region length, or None if unavailable.
58 """
60 with self._lock:
61 cached = self._seq_region_lengths.get(seq_region_name)
62 if cached is not None:
63 return cached
65 length = self._get_seq_region_length(seq_region_name)
66 if length is None:
67 return None
69 self._seq_region_lengths[seq_region_name] = length
71 return length
73 def get_sequence_by_start_end_strand(
74 self,
75 seq_region_name: str,
76 start: int,
77 end: int,
78 *,
79 strand: Strand = Strand.FORWARD,
80 ) -> str | None:
81 """Return sequence from a sequence region for the specified coordinates and strand.
83 Args:
84 seq_region_name (str): The sequence region name.
85 start (int): Start coordinate for the sequence span.
86 end (int): End coordinate for the sequence span.
87 strand (Strand): Requested strand orientation.
89 Returns:
90 str | None: The requested sequence, or None if unavailable.
91 """
93 if start < 1 or end < start:
94 raise ValueError("sequence spans must be 1-based and start must be <= end")
96 requested_length = end - start + 1
98 if self.cache is None:
99 sequence = self._load_sequence_span(seq_region_name, start, end)
100 else:
101 sequence = self.cache.get_sequence(
102 seq_region_name,
103 start,
104 end,
105 self._load_sequence_span,
106 )
108 if sequence is None: 108 ↛ 109line 108 didn't jump to line 109 because the condition on line 108 was never true
109 sequence = "N" * requested_length
110 else:
111 sequence = self._pad_to_requested_length(sequence, start, end)
113 if strand == Strand.REVERSE:
114 return reverse_complement(sequence)
116 return sequence
118 @abstractmethod
119 def close(self) -> None:
120 """Release any resources owned by the source."""
122 raise NotImplementedError
124 def __enter__(self) -> SequenceSource:
125 """Returns the source instance for use as a context manager.
127 Returns:
128 SequenceSource: The source instance.
129 """
131 return self
133 def __exit__(self, *_exc_info: object) -> None:
134 """Close the source when the context exits."""
136 self.close()
138 def _load_sequence_span(self, seq_region_name: str, start: int, end: int) -> str | None:
139 """Load a span directly from the concrete source without using cache.
141 Args:
142 seq_region_name (str): The sequence region name.
143 start (int): Start coordinate for the sequence span.
144 end (int): End coordinate for the sequence span.
146 Returns:
147 str | None: The requested sequence, or None if unavailable.
148 """
150 sequence = self._fetch_sequence_chunk(seq_region_name, start, end)
151 return self._pad_to_requested_length(sequence, start, end)
153 def _pad_to_requested_length(self, sequence: str, start: int, end: int) -> str:
154 """Pad a span with Ns when the source cannot provide the full range.
156 Args:
157 sequence (str): The sequence to pad.
158 start (int): Start coordinate for the sequence span.
159 end (int): End coordinate for the sequence span.
161 Returns:
162 str: The padded sequence.
163 """
165 requested_length = end - start + 1
166 if len(sequence) < requested_length:
167 sequence += "N" * (requested_length - len(sequence))
169 return sequence
171 def clear_cache(self) -> None:
172 """Clear derived sequence caches."""
174 with self._lock:
175 self._seq_region_lengths.clear()
177 if self.cache is not None:
178 self.cache.clear()
180 @abstractmethod
181 def _fetch_sequence_chunk(self, seq_region_name: str, start: int, end: int) -> str:
182 """Returns a forward-oriented chunk of sequence.
184 Args:
185 seq_region_name (str): The sequence region name.
186 start (int): Start coordinate for the sequence span.
187 end (int): End coordinate for the sequence span.
189 Returns:
190 str: The requested sequence chunk, padded or truncated as needed.
191 """
193 raise NotImplementedError
195 @abstractmethod
196 def _get_seq_region_length(self, seq_region_name: str) -> int | None:
197 """Returns the sequence region length if available.
199 Args:
200 seq_region_name (str): The sequence region name.
202 Returns:
203 int | None: The sequence region length, or None if unknown.
204 """
206 raise NotImplementedError