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

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.""" 

15 

16from __future__ import annotations 

17 

18from abc import ABC, abstractmethod 

19from threading import RLock 

20 

21from attrs import define, field 

22 

23from ensembl.vep.caches import SequenceCache 

24from ensembl.vep.common import Strand, reverse_complement 

25 

26 

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

28class SequenceSource(ABC): 

29 """Unified interface for sources that provide sequence for slices.""" 

30 

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) 

34 

35 @property 

36 def sequence_region_names(self) -> frozenset[str]: 

37 """Return the sequence-region names this source declares. 

38 

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. 

43 

44 Returns: 

45 frozenset[str]: The declared names, empty when the source lists none. 

46 """ 

47 

48 return frozenset() 

49 

50 def get_seq_region_length(self, seq_region_name: str) -> int | None: 

51 """Return the length of a sequence region, caching when available. 

52 

53 Args: 

54 seq_region_name (str): The sequence region name. 

55 

56 Returns: 

57 int | None: The sequence region length, or None if unavailable. 

58 """ 

59 

60 with self._lock: 

61 cached = self._seq_region_lengths.get(seq_region_name) 

62 if cached is not None: 

63 return cached 

64 

65 length = self._get_seq_region_length(seq_region_name) 

66 if length is None: 

67 return None 

68 

69 self._seq_region_lengths[seq_region_name] = length 

70 

71 return length 

72 

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. 

82 

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. 

88 

89 Returns: 

90 str | None: The requested sequence, or None if unavailable. 

91 """ 

92 

93 if start < 1 or end < start: 

94 raise ValueError("sequence spans must be 1-based and start must be <= end") 

95 

96 requested_length = end - start + 1 

97 

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 ) 

107 

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) 

112 

113 if strand == Strand.REVERSE: 

114 return reverse_complement(sequence) 

115 

116 return sequence 

117 

118 @abstractmethod 

119 def close(self) -> None: 

120 """Release any resources owned by the source.""" 

121 

122 raise NotImplementedError 

123 

124 def __enter__(self) -> SequenceSource: 

125 """Returns the source instance for use as a context manager. 

126 

127 Returns: 

128 SequenceSource: The source instance. 

129 """ 

130 

131 return self 

132 

133 def __exit__(self, *_exc_info: object) -> None: 

134 """Close the source when the context exits.""" 

135 

136 self.close() 

137 

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. 

140 

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. 

145 

146 Returns: 

147 str | None: The requested sequence, or None if unavailable. 

148 """ 

149 

150 sequence = self._fetch_sequence_chunk(seq_region_name, start, end) 

151 return self._pad_to_requested_length(sequence, start, end) 

152 

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. 

155 

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. 

160 

161 Returns: 

162 str: The padded sequence. 

163 """ 

164 

165 requested_length = end - start + 1 

166 if len(sequence) < requested_length: 

167 sequence += "N" * (requested_length - len(sequence)) 

168 

169 return sequence 

170 

171 def clear_cache(self) -> None: 

172 """Clear derived sequence caches.""" 

173 

174 with self._lock: 

175 self._seq_region_lengths.clear() 

176 

177 if self.cache is not None: 

178 self.cache.clear() 

179 

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. 

183 

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. 

188 

189 Returns: 

190 str: The requested sequence chunk, padded or truncated as needed. 

191 """ 

192 

193 raise NotImplementedError 

194 

195 @abstractmethod 

196 def _get_seq_region_length(self, seq_region_name: str) -> int | None: 

197 """Returns the sequence region length if available. 

198 

199 Args: 

200 seq_region_name (str): The sequence region name. 

201 

202 Returns: 

203 int | None: The sequence region length, or None if unknown. 

204 """ 

205 

206 raise NotImplementedError