Coverage for src/python/ensembl/vep/workflow/tracks/consequence/transcript.py: 97%

166 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 transcript consequence track and its candidate lookup. 

15 

16The track holds the whole run path for transcript consequences: the transcript source, the caches 

17that make a payload's windows cheap, the pairing rule, the annotator, and the alleles the results 

18are attached to. Pairing and the fetch window are built by their own functions as well, because 

19explaining one derivation must use the same rule the run uses without wanting any of the caching 

20around it. 

21""" 

22 

23from __future__ import annotations 

24 

25import logging 

26from bisect import bisect_left, bisect_right 

27from collections.abc import Sequence 

28from typing import Any 

29 

30from attrs import asdict, define, field 

31 

32from ensembl.vep.annotators.factory import build_annotator 

33from ensembl.vep.caches import BinnedCache, BinnedFeatureCache, Interval, TranscriptPool 

34from ensembl.vep.common import Readthrough 

35from ensembl.vep.common.constants import UNKNOWN_VALUE 

36from ensembl.vep.config import Config 

37from ensembl.vep.matcher import OverlapMatcher 

38from ensembl.vep.models.genic import Transcript 

39from ensembl.vep.models.overlap import OverlapConsequence, TranscriptVariationAllele 

40from ensembl.vep.models.variation import Variation 

41from ensembl.vep.overlaps import CandidateLookup, TranscriptOverlapFinder 

42from ensembl.vep.overlaps.base import VariationAlleleBuffer 

43from ensembl.vep.sources.build import TranscriptSource, build_transcript_source 

44from ensembl.vep.workflow.tracks.base import ( 

45 AnnotationTrack, 

46 OverlapAnnotationTrack, 

47 TrackResources, 

48 TrackResult, 

49) 

50from ensembl.vep.workflow.tracks.registry import register_track 

51 

52__all__ = [ 

53 "TranscriptCandidateLookup", 

54 "TranscriptConsequenceTrack", 

55 "build_transcript_overlap_finder", 

56 "build_transcript_tracks", 

57 "transcript_candidate_window", 

58] 

59 

60logger = logging.getLogger(__name__) 

61 

62TRACK_IDENTIFIER = "transcript" 

63"""The identifier the transcript consequence track is configured under.""" 

64 

65 

66def transcript_candidate_window(config: Config) -> int: 

67 """Return the bases added each side of an allele before transcripts are fetched. 

68 

69 The wider of the two distances: which one applies depends on each transcript's strand, and the 

70 overlap finder is what decides that once they are fetched. 

71 """ 

72 return max(config.source.upstream_distance, config.source.downstream_distance) 

73 

74 

75def build_transcript_overlap_finder( 

76 config: Config, 

77 candidates: CandidateLookup[Transcript], 

78) -> TranscriptOverlapFinder: 

79 """Return the rule pairing transcripts with alleles, over a caller's own candidates. 

80 

81 The one definition of which ``(allele, transcript)`` pairs exist. A run reaches it through its 

82 track, which fetches candidates from a cached source; ``vep explain`` reaches it with the 

83 transcripts it already found, so an explanation is never a second opinion about the pairing. 

84 

85 Args: 

86 config (Config): The run's configuration, for the distances and readthrough policy. 

87 candidates (CandidateLookup[Transcript]): Return the transcripts an input buffer may pair with. 

88 

89 Returns: 

90 TranscriptOverlapFinder: The configured finder. 

91 """ 

92 readthrough = config.annotation.readthrough 

93 return TranscriptOverlapFinder( 

94 candidates=candidates, 

95 matcher=OverlapMatcher(), 

96 readthrough=Readthrough[readthrough.upper()] if isinstance(readthrough, str) else readthrough, 

97 upstream_distance=config.source.upstream_distance, 

98 downstream_distance=config.source.downstream_distance, 

99 ) 

100 

101 

102@register_track("consequence.transcript") 

103def build_transcript_tracks( 

104 config: Config, 

105 resources: TrackResources, 

106) -> tuple[AnnotationTrack[Any], ...]: 

107 """Build the transcript consequence track a run always annotates with. 

108 

109 Raises: 

110 ValueError: If the transcript files are ambiguous or absent. 

111 NotImplementedError: If the configured transcript provider has no reader yet. 

112 """ 

113 source = build_transcript_source( 

114 resources.source_config, 

115 sequence_source=resources.sequence_source, 

116 synonyms=resources.synonyms, 

117 ) 

118 lookup = TranscriptCandidateLookup( 

119 source=source, 

120 window=transcript_candidate_window(config), 

121 pool=TranscriptPool(max_bytes=config.execution.transcript_pool_bytes), 

122 ) 

123 return ( 

124 TranscriptConsequenceTrack( 

125 identifier=TRACK_IDENTIFIER, 

126 lookup=lookup, 

127 overlap_finder=build_transcript_overlap_finder(config, lookup.candidates), 

128 annotator=build_annotator( 

129 **asdict(config.annotation), 

130 upstream_distance=config.source.upstream_distance, 

131 downstream_distance=config.source.downstream_distance, 

132 ), 

133 batch_size=config.annotation.batch_size, 

134 ), 

135 ) 

136 

137 

138class _CoverageIndex: 

139 """Merged genomic query coverage for one sequence region. 

140 

141 Replaces an ``any(...)`` scan over every previously queried interval with a ``bisect`` over a 

142 merged, much shorter list. ``contains`` can return True for a query no single old interval 

143 covered on its own -- when the query lies inside a run of *strictly overlapping* merged 

144 intervals, it is still a hit. That is safe here: a transcript overlapping the query then 

145 overlaps one of the intervals in that run, and was already fetched and cached when that 

146 interval was added. 

147 

148 Touching intervals (``previous.end + 1 == next.start``) are kept as separate entries rather 

149 than merged, since only strictly-overlapping merges (a shared coordinate) have been checked 

150 against this invariant. 

151 """ 

152 

153 __slots__ = ("_starts", "_ends") 

154 

155 def __init__(self) -> None: 

156 self._starts: list[int] = [] 

157 self._ends: list[int] = [] 

158 

159 def contains(self, interval: Interval) -> bool: 

160 """Return whether some already-added interval fully contains ``interval``.""" 

161 query_start = interval.lookup_start 

162 query_end = interval.lookup_end 

163 index = bisect_right(self._starts, query_start) - 1 

164 return index >= 0 and self._ends[index] >= query_end 

165 

166 def add(self, interval: Interval) -> None: 

167 """Merge a newly queried interval into the tracked set.""" 

168 start = interval.lookup_start 

169 end = interval.lookup_end 

170 

171 insert_at = bisect_left(self._starts, start) 

172 if insert_at > 0 and self._ends[insert_at - 1] >= start: 

173 insert_at -= 1 

174 start = self._starts[insert_at] 

175 end = max(end, self._ends[insert_at]) 

176 

177 # insert_at is either the existing entry just merged into start/end above, or a pure 

178 # insertion point with nothing there yet -- either way, scan forward from it (not past 

179 # it) for further entries the (possibly widened) interval now reaches. 

180 merge_end = insert_at 

181 while merge_end < len(self._starts) and self._starts[merge_end] <= end: 

182 end = max(end, self._ends[merge_end]) 

183 merge_end += 1 

184 

185 self._starts[insert_at:merge_end] = [start] 

186 self._ends[insert_at:merge_end] = [end] 

187 

188 

189def _coalesced_intervals(intervals: list[Interval]) -> list[Interval]: 

190 """Merge overlapping or directly adjacent source-query intervals.""" 

191 ordered = sorted(intervals, key=lambda interval: (interval.lookup_start, interval.lookup_end)) 

192 coalesced: list[Interval] = [] 

193 for interval in ordered: 

194 if not coalesced or interval.lookup_start > coalesced[-1].lookup_end + 1: 

195 coalesced.append(interval) 

196 continue 

197 previous = coalesced[-1] 

198 coalesced[-1] = Interval( 

199 start=previous.lookup_start, 

200 end=max(previous.lookup_end, interval.lookup_end), 

201 ) 

202 return coalesced 

203 

204 

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

206class TranscriptCandidateLookup: 

207 """Cached transcript lookup for an input buffer. 

208 

209 Attributes: 

210 source (TranscriptSource): The transcript source every lookup reads. 

211 window (int): Bases added each side of an allele before querying. 

212 pool (TranscriptPool): Bounded cache of built transcripts, kept across payloads. 

213 """ 

214 

215 source: TranscriptSource 

216 window: int 

217 pool: TranscriptPool 

218 _cache: BinnedCache[Transcript] = field(factory=BinnedFeatureCache, init=False) 

219 _queried_regions: dict[str, _CoverageIndex] = field(factory=dict, init=False) 

220 _uses_complete_source_fallback: bool = field(default=False, init=False) 

221 

222 def __attrs_post_init__(self) -> None: 

223 """Attach the pool to the source that builds transcripts through it. 

224 

225 ``transcript_pool`` is declared on ``GXFTranscriptSource``, which both members of the 

226 ``TranscriptSource`` union subclass; naming the assignment keeps that requirement explicit 

227 rather than accidental via the union. 

228 """ 

229 self.source.transcript_pool = self.pool 

230 

231 def begin_payload(self) -> None: 

232 """Release transcript state retained by the previous payload. 

233 

234 ``pool`` is deliberately not cleared: it is a bounded, per-worker cache of built 

235 transcripts meant to persist across payloads -- see its own docstring and the module 

236 docstring on ``caches/feature_pool.py``. 

237 """ 

238 self._cache.clear() 

239 self._queried_regions.clear() 

240 

241 def log_statistics(self) -> None: 

242 """Log the transcript pool's running counters, cheap enough to do every payload.""" 

243 logger.debug( 

244 "transcript pool: hits=%d misses=%d evictions=%d region_evictions=%d poisoned=%s", 

245 self.pool.hit_count, 

246 self.pool.miss_count, 

247 self.pool.eviction_count, 

248 self.pool.seq_region_eviction_count, 

249 self.source.transcript_pool_poisoned, 

250 ) 

251 

252 def close(self) -> None: 

253 """Close the transcript source.""" 

254 self.source.close() 

255 

256 def candidates(self, input_buffer: VariationAlleleBuffer) -> list[Transcript]: 

257 """Return each transcript that can pair with this one-region buffer.""" 

258 candidates: dict[int, Transcript] = {} 

259 intervals_by_region: dict[str, list[Interval]] = {} 

260 for allele in input_buffer.objects: 

261 region = allele.slice.seq_region_name if allele.slice is not None else None 

262 if region is None: 262 ↛ 263line 262 didn't jump to line 263 because the condition on line 262 was never true

263 continue 

264 intervals_by_region.setdefault(region, []).append( 

265 Interval( 

266 start=max(1, min(allele.start, allele.end) - self.window), 

267 end=max(allele.start, allele.end) + self.window, 

268 ) 

269 ) 

270 

271 source_intervals = { 

272 region: _coalesced_intervals(intervals) for region, intervals in intervals_by_region.items() 

273 } 

274 if self._uses_complete_source_fallback: 

275 self._load_complete_source(source_intervals) 

276 else: 

277 for region, intervals in source_intervals.items(): 

278 if self._load_region(region, intervals): 

279 continue 

280 self._cache.clear() 

281 self._queried_regions.clear() 

282 self._load_complete_source(source_intervals) 

283 break 

284 

285 for region, intervals in intervals_by_region.items(): 

286 for transcript in self._cache.get_objects(region, intervals): 

287 candidates[id(transcript)] = transcript 

288 return list(candidates.values()) 

289 

290 def _load_region(self, sequence_region: str, intervals: list[Interval]) -> bool: 

291 """Load indexed transcript graphs and report whether regional access succeeded.""" 

292 if self._uses_complete_source_fallback: 292 ↛ 293line 292 didn't jump to line 293 because the condition on line 292 was never true

293 return False 

294 coverage = self._queried_regions.setdefault(sequence_region, _CoverageIndex()) 

295 for interval in intervals: 

296 if coverage.contains(interval): 

297 continue 

298 try: 

299 transcripts = self.source.get_features_by_region( 

300 seq_region_name=sequence_region, 

301 start=interval.lookup_start, 

302 end=interval.lookup_end, 

303 ) 

304 except OSError: 

305 logger.warning( 

306 "%s has no usable region index; scanning each payload by gene", 

307 self.source.file_path, 

308 ) 

309 self._uses_complete_source_fallback = True 

310 return False 

311 for transcript in transcripts: 

312 self._cache.add( 

313 sequence_region, 

314 transcript, 

315 Interval(start=transcript.start, end=transcript.end), 

316 key=(sequence_region, transcript.stable_id, transcript.start, transcript.end), 

317 ) 

318 coverage.add(interval) 

319 return True 

320 

321 def _load_complete_source(self, intervals_by_region: dict[str, list[Interval]]) -> None: 

322 """Stream an unindexed GXF and retain only features needed by this payload.""" 

323 uncovered: dict[str, list[Interval]] = {} 

324 for sequence_region, intervals in intervals_by_region.items(): 

325 coverage = self._queried_regions.setdefault(sequence_region, _CoverageIndex()) 

326 for interval in intervals: 

327 if coverage.contains(interval): 

328 continue 

329 uncovered.setdefault(sequence_region, []).append(interval) 

330 if not uncovered: 

331 return 

332 

333 source_intervals = { 

334 sequence_region: [(interval.lookup_start, interval.lookup_end) for interval in intervals] 

335 for sequence_region, intervals in uncovered.items() 

336 } 

337 for transcript in self.source.iter_features_by_regions(source_intervals): 

338 sequence_region = ( 

339 transcript.slice.seq_region_name if transcript.slice is not None else UNKNOWN_VALUE 

340 ) 

341 intervals = uncovered.get(sequence_region, []) 

342 if not any( 342 ↛ 346line 342 didn't jump to line 346 because the condition on line 342 was never true

343 transcript.start <= interval.lookup_end and transcript.end >= interval.lookup_start 

344 for interval in intervals 

345 ): 

346 continue 

347 self._cache.add( 

348 sequence_region, 

349 transcript, 

350 Interval(start=transcript.start, end=transcript.end), 

351 key=(sequence_region, transcript.stable_id, transcript.start, transcript.end), 

352 ) 

353 for sequence_region, intervals in uncovered.items(): 

354 coverage = self._queried_regions[sequence_region] 

355 for interval in intervals: 

356 coverage.add(interval) 

357 self._uses_complete_source_fallback = True 

358 

359 

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

361class TranscriptConsequenceTrack(OverlapAnnotationTrack[OverlapConsequence]): 

362 """Transcript consequence annotation track. 

363 

364 Attributes: 

365 lookup (TranscriptCandidateLookup): The source and caches this track's finder reads through. 

366 """ 

367 

368 lookup: TranscriptCandidateLookup 

369 

370 def begin_payload(self, input_buffer: VariationAlleleBuffer) -> None: 

371 """Release the previous payload's transcripts and fetch this payload's in one pass. 

372 

373 Priming with the whole payload is what makes each annotation window a cache hit rather 

374 than another source query. 

375 """ 

376 self.lookup.begin_payload() 

377 self.lookup.log_statistics() 

378 self.lookup.candidates(input_buffer) 

379 

380 def attach( 

381 self, 

382 variations: Sequence[Variation], 

383 results: Sequence[TrackResult[OverlapConsequence]], 

384 ) -> None: 

385 """Attach consequences to the transcript overlaps of each allele. 

386 

387 Raises: 

388 TypeError: If a result holds an overlap this track cannot have produced. 

389 """ 

390 by_allele: dict[int, list[TranscriptVariationAllele]] = {} 

391 for result in results: 

392 overlap = result.overlap 

393 if not isinstance(overlap, TranscriptVariationAllele): 

394 raise TypeError( 

395 f"Track '{self.identifier}' cannot attach a {type(overlap).__name__} overlap." 

396 ) 

397 overlap.overlap_consequences = list(result.annotations) 

398 by_allele.setdefault(id(overlap.overlapping_feature), []).append(overlap) 

399 for variation in variations: 

400 for allele in variation.variation_alleles: 

401 allele.transcript_variation_alleles = by_allele.get(id(allele), []) 

402 

403 def close(self) -> None: 

404 """Close the transcript source this track reads.""" 

405 self.lookup.close()