Coverage for src/python/ensembl/vep/workflow/worker/annotation.py: 100%

77 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 annotation worker: a payload of unparsed input records in, detached annotations out. 

15 

16One worker per process, built after the process starts, holding what every track shares: the 

17reference sequence, the synonym map, the input source turning lines into variations, and the 

18output factory detaching what a payload produced. Which annotations are made, and from which 

19sources, belongs to the workflow's tracks rather than here. 

20 

21The input source is what reads: the worker hands it one payload's records and is given variations 

22back, so which format the input is in, and what a record of it is, stays with the source. 

23""" 

24 

25from __future__ import annotations 

26 

27import logging 

28from collections.abc import Sequence 

29from itertools import batched 

30from typing import Any 

31 

32from attrs import frozen 

33 

34from ensembl.vep.buffer import FixedSizeInputBuffer 

35from ensembl.vep.config import Config 

36from ensembl.vep.models.variation import Variation, VariationAllele 

37from ensembl.vep.output.factory.base import AnnotatedVariant 

38from ensembl.vep.output.factory.base import AnnotatedVariantFactory 

39from ensembl.vep.sources.build import ( 

40 build_chromosome_synonyms, 

41 build_input_source, 

42 build_sequence_source, 

43) 

44from ensembl.vep.stats import RunSummaryCollector, RunSummaryDelta 

45from ensembl.vep.workflow.base import Workflow 

46from ensembl.vep.workflow.build.registry import build_workflow 

47from ensembl.vep.workflow.tracks.base import TrackResources, TrackResult 

48 

49__all__ = ["AnnotationBufferResult", "AnnotationBufferWorker"] 

50 

51logger = logging.getLogger(__name__) 

52 

53 

54@frozen(kw_only=True, auto_attribs=True) 

55class AnnotationBufferResult: 

56 """Ordered worker result detached from live model objects. 

57 

58 Attributes: 

59 variants (tuple[AnnotatedVariant, ...]): Detached annotated variants. 

60 summary_delta (RunSummaryDelta): Mergeable run-summary counts. 

61 """ 

62 

63 variants: tuple[AnnotatedVariant, ...] 

64 summary_delta: RunSummaryDelta 

65 

66 

67class AnnotationBufferWorker: 

68 """Worker-local sources and workflow state for payloads of input records. 

69 

70 The ``Worker`` protocol's ``run`` for annotation, which is why nothing here is constructed 

71 until the process that annotates owns it: sources are opened and caches warmed per process. 

72 """ 

73 

74 def __init__(self, config: Config) -> None: 

75 """Build the shared sources and the configured workflow after the worker starts.""" 

76 source_config = config.source 

77 assert source_config.input_file is not None 

78 self.config = config 

79 synonyms = build_chromosome_synonyms(source_config) 

80 self.sequence_source = build_sequence_source(source_config) 

81 self.input_source = build_input_source( 

82 source_config, sequence_source=self.sequence_source, synonyms=synonyms 

83 ) 

84 self.workflow: Workflow = build_workflow( 

85 config, 

86 TrackResources( 

87 source_config=source_config, 

88 sequence_source=self.sequence_source, 

89 synonyms=synonyms, 

90 ), 

91 ) 

92 self.snapshot_factory = AnnotatedVariantFactory() 

93 self._track_identifiers = frozenset(track.identifier for track in self.workflow.tracks) 

94 

95 def run(self, records: tuple[str, ...]) -> AnnotationBufferResult: 

96 """Return detached annotations for one payload of input records.""" 

97 variations = self.input_source.records_to_features(records) 

98 unknown_regions = frozenset(self.sequence_source.unknown_regions) 

99 alleles = self._annotatable_alleles(variations, unknown_regions) 

100 annotated_variants: list[AnnotatedVariant] = [] 

101 collector = RunSummaryCollector() 

102 

103 # Each track fetches and caches what the whole batch needs once. Windows retain only 

104 # their temporary overlap graph. 

105 self.workflow.begin_payload(self._payload_buffer(alleles)) 

106 # Read here rather than in the parent: output is the only consumer of the columns, and 

107 # the parser reads the record itself. 

108 input_columns = (self.input_source.record_columns(record) for record in records) 

109 variation_columns = zip(variations, input_columns, strict=True) 

110 for group in batched(variation_columns, self.config.execution.annotation_window): 

111 group_variations = [variation for variation, _columns in group] 

112 group_alleles = self._annotatable_alleles(group_variations, unknown_regions) 

113 results: list[TrackResult[Any]] = [] 

114 if group_alleles: 

115 results = self.workflow.annotate( 

116 FixedSizeInputBuffer(objects=tuple(group_alleles)), 

117 threads=self.config.execution.threads, 

118 ) 

119 self._attach_results(group_variations, results) 

120 for variation, columns in group: 

121 region = variation.slice.seq_region_name if variation.slice is not None else None 

122 annotated_variants.append( 

123 self.snapshot_factory.build_annotated_variant( 

124 variation, 

125 columns, 

126 skipped=region in unknown_regions, 

127 ) 

128 ) 

129 collector.observe(variation) 

130 self._attach_results(group_variations, ()) 

131 return AnnotationBufferResult( 

132 variants=tuple(annotated_variants), 

133 summary_delta=collector.delta(), 

134 ) 

135 

136 @staticmethod 

137 def _payload_buffer(alleles: Sequence[VariationAllele]) -> FixedSizeInputBuffer[VariationAllele]: 

138 """Return the buffer priming every track for one whole batch. 

139 

140 The buffer is filled through its own refill policy, which is what checks that the input is 

141 sorted and that one payload names one sequence region. Its cap is the payload itself: 

142 batching already capped it at ``buffer_size`` records, and a smaller cap here would hold 

143 alleles back from the prefetch the tracks prime from. 

144 

145 Args: 

146 alleles (Sequence[VariationAllele]): Every annotatable allele the batch describes. 

147 

148 Returns: 

149 FixedSizeInputBuffer[VariationAllele]: The filled buffer. 

150 """ 

151 buffer: FixedSizeInputBuffer[VariationAllele] = FixedSizeInputBuffer(buffer_size=max(len(alleles), 1)) 

152 buffer.next(iter(alleles)) 

153 return buffer 

154 

155 def _attach_results( 

156 self, 

157 variations: Sequence[Variation], 

158 results: Sequence[TrackResult[Any]], 

159 ) -> None: 

160 """Hand each track its own results to attach, and release what the others held. 

161 

162 Every track is given a group, empty or not, so a window that found nothing for a track 

163 releases the overlaps the previous window attached for it. Attaching nothing at all is 

164 therefore how a rendered window's overlap graph is cleared. 

165 

166 Raises: 

167 ValueError: If a result names a track this workflow does not have. 

168 """ 

169 grouped: dict[str, list[TrackResult[Any]]] = {} 

170 for result in results: 

171 grouped.setdefault(result.track_identifier, []).append(result) 

172 unknown = sorted(set(grouped) - self._track_identifiers) 

173 if unknown: 

174 raise ValueError(f"workflow '{self.workflow.name}' has no track {', '.join(unknown)}") 

175 for track in self.workflow.tracks: 

176 track.attach(variations, grouped.get(track.identifier, ())) 

177 

178 @staticmethod 

179 def _annotatable_alleles( 

180 variations: Sequence[Variation], 

181 unknown_regions: frozenset[str], 

182 ) -> list[VariationAllele]: 

183 """Return alleles whose sequence region is available to annotation sources.""" 

184 alleles: list[VariationAllele] = [] 

185 for variation in variations: 

186 region = variation.slice.seq_region_name if variation.slice is not None else None 

187 if region not in unknown_regions: 

188 alleles.extend(variation.variation_alleles) 

189 return alleles