Coverage for src/python/ensembl/vep/workflow/tracks/base.py: 100%
53 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"""Annotation-track contracts and value objects.
16A track owns everything one kind of annotation needs: the source it reads, whatever it caches
17between payloads, the rule pairing features with alleles, the annotator interpreting each pair,
18and where the results are attached for output. The worker running a track supplies only what
19every track shares -- the reference sequence and the synonym map -- so adding a kind of
20annotation adds a track and changes nothing above it.
21"""
23from __future__ import annotations
25from collections.abc import Sequence
26from itertools import islice
27from typing import Generic, Protocol
29from attrs import define, field
31from ensembl.vep.annotators.base import Annotator, ResultT
32from ensembl.vep.config.sections.common.source import SourceConfig
33from ensembl.vep.models.overlap import FeatureOverlap
34from ensembl.vep.models.variation import Variation
35from ensembl.vep.overlaps import OverlapFinder
36from ensembl.vep.overlaps.base import VariationAlleleBuffer
37from ensembl.vep.sources.file.fasta.sequence import FastaSequenceSource
38from ensembl.vep.sources.synonym import ChromosomeSynonyms
40__all__ = ["AnnotationTrack", "OverlapAnnotationTrack", "TrackResources", "TrackResult"]
43@define(frozen=True, kw_only=True, auto_attribs=True)
44class TrackResources:
45 """Resources shared by every track in one workflow.
47 Built once per worker and passed to each track builder: a source reads reference sequence and
48 resolves sequence-region names through the same objects whichever track built it.
50 Attributes:
51 source_config (SourceConfig): The configured sources, for the files and distances a track reads.
52 sequence_source (FastaSequenceSource | None): The shared reference source, or None for a
53 caller that can annotate without reference sequence.
54 synonyms (ChromosomeSynonyms): The run's sequence-region synonyms.
55 """
57 source_config: SourceConfig
58 sequence_source: FastaSequenceSource | None
59 synonyms: ChromosomeSynonyms
62@define(frozen=True, kw_only=True, auto_attribs=True)
63class TrackResult(Generic[ResultT]):
64 """Annotation results for one overlap.
66 Attributes:
67 track_identifier (str): Identifier of the producing track.
68 overlap (FeatureOverlap): The overlap passed to the annotator.
69 annotations (tuple[ResultT, ...]): Values emitted for the overlap.
70 """
72 track_identifier: str
73 overlap: FeatureOverlap
74 annotations: tuple[ResultT, ...]
77class AnnotationTrack(Protocol[ResultT]):
78 """Configured annotation concern for one input buffer."""
80 @property
81 def identifier(self) -> str:
82 """Return the unique configured track identifier."""
83 raise NotImplementedError
85 def begin_payload(self, input_buffer: VariationAlleleBuffer) -> None:
86 """Release the previous payload's state and prime this one's."""
87 raise NotImplementedError
89 def annotate(self, input_buffer: VariationAlleleBuffer) -> list[TrackResult[ResultT]]:
90 """Return annotations for the input buffer."""
91 raise NotImplementedError
93 def attach(
94 self,
95 variations: Sequence[Variation],
96 results: Sequence[TrackResult[ResultT]],
97 ) -> None:
98 """Attach this track's results to the alleles output reads them from.
100 Every allele of every variation is assigned, so attaching no results releases what a
101 rendered window retained.
102 """
103 raise NotImplementedError
105 def close(self) -> None:
106 """Release the source and caches this track owns."""
107 raise NotImplementedError
110@define(kw_only=True, auto_attribs=True)
111class OverlapAnnotationTrack(Generic[ResultT]):
112 """Overlap finder and annotator for one configured concern.
114 Specialised per kind of annotation: a subclass holds the source and caches its finder reads
115 through, and attaches the results where that kind of overlap belongs.
117 Attributes:
118 identifier (str): Unique name for this configured track instance.
119 overlap_finder (OverlapFinder[FeatureOverlap]): Produce overlaps for an input buffer.
120 annotator (Annotator[ResultT]): Interpret the overlaps found by this track.
121 batch_size (int): Maximum overlaps materialised for one annotator call.
122 """
124 identifier: str
125 overlap_finder: OverlapFinder[FeatureOverlap]
126 annotator: Annotator[ResultT]
127 batch_size: int = field(default=256)
129 def __attrs_post_init__(self) -> None:
130 if self.batch_size < 1:
131 raise ValueError("Annotation track batch_size must be positive.")
133 def begin_payload(self, input_buffer: VariationAlleleBuffer) -> None:
134 """Prime nothing: a track caching between payloads overrides this."""
136 def annotate(self, input_buffer: VariationAlleleBuffer) -> list[TrackResult[ResultT]]:
137 """Return annotations for every overlap found in ``input_buffer``."""
138 results: list[TrackResult[ResultT]] = []
139 overlap_iterator = self.overlap_finder.find(input_buffer)
140 while overlaps := list(islice(overlap_iterator, self.batch_size)):
141 annotation_groups = self.annotator.annotate_feature_overlaps(overlaps)
142 if len(annotation_groups) != len(overlaps):
143 raise ValueError(
144 f"Annotator '{self.annotator.name}' returned {len(annotation_groups)} result groups "
145 f"for {len(overlaps)} overlaps."
146 )
148 for overlap, annotations in zip(overlaps, annotation_groups, strict=True):
149 results.append(
150 TrackResult(
151 track_identifier=self.identifier,
152 overlap=overlap,
153 annotations=tuple(annotations),
154 )
155 )
156 return results
158 def attach(
159 self,
160 variations: Sequence[Variation],
161 results: Sequence[TrackResult[ResultT]],
162 ) -> None:
163 """Reject results no subclass claimed, rather than dropping them silently.
165 Raises:
166 NotImplementedError: Always. A track that produces results owns where they go.
167 """
168 raise NotImplementedError(f"Track '{self.identifier}' does not attach its results.")
170 def close(self) -> None:
171 """Release nothing: a track owning a source overrides this."""