Coverage for src/python/ensembl/vep/sources/feature_source.py: 100%

34 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"""The feature source contract. 

15 

16Reading and model building are two halves. The record getters answer in whatever the source's own 

17records are -- what the format holds, before anything has been interpreted -- and 

18``records_to_features`` turns a set of them into models. The feature getters are those two 

19composed, which is why they are concrete here: a source implements the record half and gets the 

20feature half. A format that assembles one feature from several records (GFF3, GTF) overrides the 

21feature getters, because a record at a time is not enough to build anything complete. 

22""" 

23 

24from __future__ import annotations 

25 

26from abc import ABC, abstractmethod 

27from collections.abc import Iterator 

28from typing import Generic, TypeVar 

29from attr import define, field 

30 

31from ensembl.vep.caches import SliceCache, WeakSliceCache 

32from ensembl.vep.common import SourceType 

33from ensembl.vep.models import Feature 

34from ensembl.vep.sources.sequence_source import SequenceSource 

35 

36F = TypeVar("F", bound=Feature) 

37R = TypeVar("R") 

38"""One of the source's own records, as its format holds it.""" 

39 

40 

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

42class FeatureSource(ABC, Generic[R, F]): 

43 """Source of domain feature objects. 

44 

45 Attributes: 

46 source_type (SourceType): Kind of backing source. 

47 sequence_source (SequenceSource | None): Optional reference sequence source. 

48 slice_cache (SliceCache): Shared genomic slice cache. 

49 """ 

50 

51 source_type: SourceType 

52 sequence_source: SequenceSource | None = field(default=None) 

53 slice_cache: SliceCache = field(factory=WeakSliceCache) 

54 

55 @abstractmethod 

56 def get_all_records(self) -> list[R]: 

57 """Return every unconverted record held by this source.""" 

58 

59 raise NotImplementedError 

60 

61 @abstractmethod 

62 def iter_all_records(self) -> Iterator[R]: 

63 """Yield every unconverted record held by this source.""" 

64 

65 raise NotImplementedError 

66 

67 @abstractmethod 

68 def get_records_by_region( 

69 self, 

70 region: str | None = None, 

71 *, 

72 seq_region_name: str | None = None, 

73 start: int | None = None, 

74 end: int | None = None, 

75 **kwargs: object, 

76 ) -> list[R]: 

77 """Return unconverted records overlapping a genomic region. 

78 

79 Args: 

80 region (str | None): The region (e.g., "chr1:1000-2000") to get records from. 

81 seq_region_name (str | None): The name of the region to get records from. 

82 start (int | None): The start position of the region to get records from. 

83 end (int | None): The end position of the region to get records from. 

84 **kwargs (object): What a format's own query accepts, such as the record types a GXF 

85 query may filter to before a line is parsed. 

86 

87 Returns: 

88 list[R]: The records overlapping the specified region. 

89 """ 

90 

91 raise NotImplementedError 

92 

93 @abstractmethod 

94 def iter_records_by_region( 

95 self, 

96 region: str | None = None, 

97 *, 

98 seq_region_name: str | None = None, 

99 start: int | None = None, 

100 end: int | None = None, 

101 **kwargs: object, 

102 ) -> Iterator[R]: 

103 """Yield unconverted records overlapping a genomic region. 

104 

105 Args: 

106 region (str | None): The region (e.g., "chr1:1000-2000") to get records from. 

107 seq_region_name (str | None): The name of the region to get records from. 

108 start (int | None): The start position of the region to get records from. 

109 end (int | None): The end position of the region to get records from. 

110 **kwargs (object): What a format's own query accepts. 

111 

112 Returns: 

113 Iterator[R]: The records overlapping the specified region. 

114 """ 

115 

116 raise NotImplementedError 

117 

118 @abstractmethod 

119 def records_to_features(self, records: list[R]) -> list[F]: 

120 """Return the features described by records from this source. 

121 

122 Args: 

123 records (list[R]): The records to convert, in the order the source read them. 

124 

125 Returns: 

126 list[F]: The features they describe. 

127 """ 

128 

129 raise NotImplementedError 

130 

131 def get_all_features(self) -> list[F]: 

132 """Return all features from this source.""" 

133 

134 return self.records_to_features(self.get_all_records()) 

135 

136 def iter_all_features(self) -> Iterator[F]: 

137 """Yield all features from this source. 

138 

139 One record at a time, which only a format whose record carries a whole feature can do. 

140 A format that assembles a feature from several records overrides this. 

141 """ 

142 

143 for record in self.iter_all_records(): 

144 yield from self.records_to_features([record]) 

145 

146 def get_features_by_region( 

147 self, 

148 region: str | None = None, 

149 *, 

150 seq_region_name: str | None = None, 

151 start: int | None = None, 

152 end: int | None = None, 

153 ) -> list[F]: 

154 """Return features overlapping a genomic region. 

155 

156 Args: 

157 region (str | None): The region (e.g., "chr1:1000-2000") to get features from. 

158 seq_region_name (str | None): The name of the region to get features from. 

159 start (int | None): The start position of the region to get features from. 

160 end (int | None): The end position of the region to get features from. 

161 

162 Returns: 

163 list[F]: A list of features overlapping the specified region. 

164 """ 

165 

166 return self.records_to_features( 

167 self.get_records_by_region(region, seq_region_name=seq_region_name, start=start, end=end) 

168 ) 

169 

170 def iter_features_by_region( 

171 self, 

172 region: str | None = None, 

173 *, 

174 seq_region_name: str | None = None, 

175 start: int | None = None, 

176 end: int | None = None, 

177 ) -> Iterator[F]: 

178 """Yield features overlapping a genomic region. 

179 

180 Args: 

181 region (str | None): The region (e.g., "chr1:1000-2000") to get features from. 

182 seq_region_name (str | None): The name of the region to get features from. 

183 start (int | None): The start position of the region to get features from. 

184 end (int | None): The end position of the region to get features from. 

185 

186 Returns: 

187 Iterator[F]: An iterator over features overlapping the specified region. 

188 """ 

189 

190 records = self.iter_records_by_region(region, seq_region_name=seq_region_name, start=start, end=end) 

191 for record in records: 

192 yield from self.records_to_features([record]) 

193 

194 def record_count(self, *, scan: bool = False) -> int | None: # pylint: disable=unused-argument 

195 """Return the declared record count, if available. 

196 

197 Concrete and None by default: a count is optional metadata, not something every source 

198 can answer. A source whose format carries one -- an indexed file, a table a query can 

199 count -- overrides this; the rest say they do not know, and a caller such as progress 

200 reporting does without rather than paying for a count. 

201 

202 Args: 

203 scan (bool): Whether to count the hard way when nothing declares it, which for a 

204 file-backed source means reading the whole input. Default is False. 

205 

206 Returns: 

207 int | None: The record count, or None when this source cannot answer. 

208 """ 

209 

210 return None 

211 

212 @abstractmethod 

213 def close(self) -> None: 

214 """Release resources held by this source (e.g., close file handles or DB connections).""" 

215 

216 raise NotImplementedError 

217 

218 def __enter__(self) -> FeatureSource[R, F]: 

219 return self 

220 

221 def __exit__(self, *exc_info: object) -> None: 

222 self.close()