Coverage for src/python/ensembl/vep/workflow/base.py: 100%
48 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"""An annotation workflow over an input buffer."""
16from __future__ import annotations
18from concurrent.futures import ThreadPoolExecutor
19from types import TracebackType
20from typing import Any
22from attrs import define
24from ensembl.vep.overlaps.base import VariationAlleleBuffer
25from ensembl.vep.workflow.tracks.base import AnnotationTrack, TrackResult
27__all__ = ["Workflow"]
30@define(kw_only=True, auto_attribs=True)
31class Workflow:
32 """Ordered annotation tracks for an input buffer.
34 A workflow owns its tracks, and a track owns the source it reads, so a workflow holds live
35 per-worker state and is built inside the process that annotates with it.
37 Attributes:
38 name (str): Workflow implementation name.
39 tracks (tuple[AnnotationTrack[Any], ...]): Ordered runtime tracks.
40 """
42 name: str
43 tracks: tuple[AnnotationTrack[Any], ...]
45 def __attrs_post_init__(self) -> None:
46 identifiers = [track.identifier for track in self.tracks]
47 if len(set(identifiers)) != len(identifiers):
48 raise ValueError("Workflow tracks must have unique identifiers.")
50 def __enter__(self) -> Workflow:
51 """Return the workflow, whose tracks hold their sources open."""
52 return self
54 def __exit__(
55 self,
56 exception_type: type[BaseException] | None,
57 exception: BaseException | None,
58 traceback: TracebackType | None,
59 ) -> None:
60 """Close every track's source."""
61 self.close()
63 def track(self, identifier: str) -> AnnotationTrack[Any]:
64 """Return the track that produced results under ``identifier``.
66 Raises:
67 KeyError: If no track in this workflow has that identifier.
68 """
69 for track in self.tracks:
70 if track.identifier == identifier:
71 return track
72 raise KeyError(f"Workflow '{self.name}' has no track '{identifier}'.")
74 def begin_payload(self, input_buffer: VariationAlleleBuffer) -> None:
75 """Release the previous payload's state and prime each track for this one.
77 The whole payload is passed, not one annotation window, so a track fetches and caches what
78 the payload needs once rather than once per window.
79 """
80 for track in self.tracks:
81 track.begin_payload(input_buffer)
83 def annotate(
84 self,
85 input_buffer: VariationAlleleBuffer,
86 *,
87 threads: int = 1,
88 ) -> list[TrackResult[Any]]:
89 """Return ordered results from every track.
91 Args:
92 input_buffer (VariationAlleleBuffer): Read-only input for every track.
93 threads (int): Maximum independently runnable tracks.
95 Returns:
96 list[TrackResult[Any]]: Results ordered by declared track order.
98 Raises:
99 ValueError: If ``threads`` is less than one.
100 """
101 if threads < 1:
102 raise ValueError("Workflow thread count must be positive.")
103 if threads == 1 or len(self.tracks) < 2:
104 return self._annotate_serial(input_buffer)
106 workers = min(threads, len(self.tracks))
107 with ThreadPoolExecutor(max_workers=workers) as executor:
108 futures = [executor.submit(track.annotate, input_buffer) for track in self.tracks]
109 results: list[TrackResult[Any]] = []
110 for future in futures:
111 results.extend(future.result())
112 return results
114 def close(self) -> None:
115 """Close every track's source."""
116 for track in self.tracks:
117 track.close()
119 def _annotate_serial(self, input_buffer: VariationAlleleBuffer) -> list[TrackResult[Any]]:
120 """Return ordered results without creating worker threads."""
121 results: list[TrackResult[Any]] = []
122 for track in self.tracks:
123 results.extend(track.annotate(input_buffer))
124 return results