Coverage for src/python/ensembl/vep/models/variation/variation_allele.py: 97%
121 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"""VariationAllele class."""
16from __future__ import annotations
18import logging
19from typing import TYPE_CHECKING
20from functools import cached_property
21from threading import RLock
22from collections.abc import Sequence
23from attrs import define, field
25from ensembl.vep.common import (
26 Locus,
27 trim_sequences,
28 shift_sequence,
29 invalidates,
30 resets_attrs,
31)
32from ensembl.vep.common.constants import EMPTY_ALLELE, UNKNOWN_VALUE
33from ensembl.vep.models import Feature
35if TYPE_CHECKING:
36 from ensembl.vep.models.overlap import OverlapConsequence, FeatureOverlap, TranscriptVariationAllele
37 from ensembl.vep.models.variation.variation import Variation
39logger = logging.getLogger(__name__)
40MAX_SEARCH_AREA = 1000
43@define(kw_only=True, auto_attribs=True)
44class VariationAllele(Feature):
45 """Represents a specific allele of a variation.
47 Attributes:
48 start (int):
49 The start position in relative to slice.
50 end (int):
51 The end position in relative to slice.
52 reference_allele (str | None):
53 The reference allele.
54 alternate_allele (str | None):
55 The alternate allele.
56 variation (Variation | None):
57 Variation that owns this allele.
58 transcript_variation_alleles (list[TranscriptVariationAllele]):
59 List of overlaps between this variation allele and transcripts.
60 original_locus (Locus | None):
61 The original locus of the variation allele before any minimisation or shifting.
62 minimised_locus (Locus | None):
63 The locus of the variation allele after minimisation.
64 shifted_locus (Locus | None):
65 The locus of the variation allele after shifting.
66 minimised (bool):
67 Whether the variation allele has been minimised.
68 shifted (bool):
69 Whether the variation allele has been shifted.
70 """
72 start: int = field(
73 on_setattr=[resets_attrs(("_shifted", False), ("_minimised_locus", None), ("_shifted_locus", None))]
74 )
75 end: int = field(
76 on_setattr=[resets_attrs(("_shifted", False), ("_minimised_locus", None), ("_shifted_locus", None))]
77 )
78 reference_allele: str | None = field(
79 default=None,
80 on_setattr=[
81 resets_attrs(
82 ("_minimised", False),
83 ("_shifted", False),
84 ("_minimised_locus", None),
85 ("_shifted_locus", None),
86 )
87 ],
88 )
89 alternate_allele: str | None = field(
90 default=None,
91 on_setattr=[
92 resets_attrs(
93 ("_minimised", False),
94 ("_shifted", False),
95 ("_minimised_locus", None),
96 ("_shifted_locus", None),
97 )
98 ],
99 )
100 variation: Variation | None = field(default=None, repr=False, eq=False)
101 """The variation that owns this allele, if available."""
102 _original_locus: Locus | None = field(default=None, init=False)
103 """The original locus of the variation allele before any minimisation or shifting (if any occurred)."""
104 _minimised: bool = field(default=False, init=False)
105 """Whether the variation allele has been minimised."""
106 _minimised_locus: Locus | None = field(default=None, init=False)
107 _shifted: bool = field(default=False, init=False)
108 """Whether the variation allele has been shifted."""
109 _shifted_locus: Locus | None = field(default=None, init=False)
110 _lock: RLock = field(factory=RLock, init=False, repr=False)
111 transcript_variation_alleles: list[TranscriptVariationAllele] = field(
112 factory=list, init=False, on_setattr=invalidates("_overlap_consequences")
113 )
114 # regulatory_variation_alleles: list[RegulatoryVariationAllele] = field(factory=list, init=False)
115 # motif_variation_alleles: list[MotifVariationAllele] = field(factory=list, init=False)
116 # intergenic_variation_alleles: list[IntergenicVariationAllele] = field(factory=list, init=False)
118 @property
119 def _locus(self) -> Locus:
120 return Locus(
121 start=self.start, end=self.end, allele_string=f"{self.reference_allele}/{self.alternate_allele}"
122 )
124 @property
125 def original_locus(self) -> Locus | None:
126 """Public accessor for _original_locus.
128 Returns:
129 Locus | None: The original locus if available, None otherwise.
130 """
131 return self._original_locus
133 @property
134 def minimised_locus(self) -> Locus | None:
135 """Public accessor for _minimised_locus.
137 Returns:
138 Locus | None: The minimised locus if available, None otherwise.
139 """
140 return self._minimised_locus
142 @property
143 def shifted_locus(self) -> Locus | None:
144 """Public accessor for _shifted_locus.
146 Returns:
147 Locus | None: The shifted locus if available, None otherwise.
148 """
149 return self._shifted_locus
151 @property
152 def minimised(self) -> bool:
153 """Public accessor for _minimised.
155 Returns:
156 bool: True if the variation allele has been minimised, False otherwise.
157 """
158 return self._minimised
160 @property
161 def shifted(self) -> bool:
162 """Public accessor for _shifted.
164 Returns:
165 bool: True if the variation allele has been shifted, False otherwise.
166 """
167 return self._shifted
169 @property
170 def _locus_name(self) -> str:
171 """``CHR:POS:REF>ALT`` as variation allele name."""
172 seq_region_name = self.slice.seq_region_name if self.slice is not None else UNKNOWN_VALUE
173 reference_allele = self.reference_allele or EMPTY_ALLELE
174 alternate_allele = self.alternate_allele or EMPTY_ALLELE
175 return f"{seq_region_name}:{self.start}:{reference_allele}>{alternate_allele}"
177 @property
178 def display_name(self) -> str:
179 """Return a unique displayable name this allele is identified by.
181 The variation stable_id for a multi-allelic record is not unique for each allele. This
182 allele's alternate is appended to make it unique. If there is not stable_id generate
183 the name using locus.
185 Returns:
186 str: The variant's identifier, that identifier and this alternate allele, or this
187 allele's locus name.
188 """
189 variation = self.variation
190 if variation is None or not variation.stable_id:
191 return self._locus_name
192 if len(variation.variation_alleles) > 1:
193 return f"{variation.stable_id}:{self.alternate_allele or EMPTY_ALLELE}"
194 return variation.stable_id
196 def minimise(self, force: bool = False) -> None:
197 """Minimises the variation allele by computing the minimal representation of the variant.
199 This method also stores the original locus information before minimisation.
201 Args:
202 force (bool): If True, force minimisation even if already minimised.
204 Raises:
205 ValueError: If reference or alternate allele is None.
206 """
207 if self.minimised and not force:
208 logger.debug("Variation allele is already minimised. Use force=True to re-minimise.")
209 return
211 if self.reference_allele is None or self.alternate_allele is None:
212 raise ValueError("Missing reference or alternate allele for minimisation")
214 original_locus = self._original_locus or self._locus
216 new_ref, new_alt, new_start, new_end, _changed = trim_sequences(
217 ref=self.reference_allele, alt=self.alternate_allele, start=self.start, end=self.end
218 )
220 if _changed:
221 self.reference_allele = new_ref
222 self.alternate_allele = new_alt
223 self.start = new_start
224 self.end = new_end
226 self._original_locus = self._original_locus or original_locus
227 self._minimised_locus = self._locus
228 self._minimised = True
230 def shift(self, force: bool = False) -> None:
231 """Shifts the variation allele to the leftmost position in the sequence.
233 This method also stores the original locus information before shifting.
235 Args:
236 force (bool): If True, force shifting even if already shifted.
238 Raises:
239 ValueError: If reference or alternate allele is None.
240 """
241 if self.shifted and not force: 241 ↛ 242line 241 didn't jump to line 242 because the condition on line 241 was never true
242 logger.debug("Variation allele is already shifted. Use force=True to re-shift.")
243 return
245 if self.reference_allele is None or self.alternate_allele is None:
246 raise ValueError("Missing reference or alternate allele for shifting")
248 if self.slice is None or self.slice.seq is None: 248 ↛ 249line 248 didn't jump to line 249 because the condition on line 248 was never true
249 raise ValueError("Cannot shift variation allele without attached slice sequence.")
251 original_locus = self._original_locus or self._locus
253 search_start = max(0, self.start - MAX_SEARCH_AREA - 1)
254 search_end = min(self.slice.end, self.end + MAX_SEARCH_AREA)
255 pre_seq = self.slice.seq[search_start : (self.start - 1)]
256 post_seq = self.slice.seq[self.end : search_end]
257 if len(self.reference_allele) < len(self.alternate_allele):
258 # for insertions, we check alternate allele
259 seq_to_check = self.alternate_allele
260 using_ref = False
261 else:
262 # for SNV and deletions, we check reference allele
263 seq_to_check = self.reference_allele
264 using_ref = True
266 _, shifted_seq, new_start, new_end, _changed = shift_sequence(
267 seq=seq_to_check, post_seq=post_seq, pre_seq=pre_seq, start=self.start, end=self.end
268 )
270 if _changed:
271 if using_ref:
272 self.reference_allele = shifted_seq
273 else:
274 self.alternate_allele = shifted_seq
276 self.start = new_start
277 self.end = new_end
279 self._original_locus = self._original_locus or original_locus
280 self._shifted_locus = self._locus
281 self._shifted = True
283 @property
284 def overlap_consequences(self) -> list[OverlapConsequence]:
285 """Public accessor for _overlap_consequences.
287 Returns:
288 list[OverlapConsequence]: The list of overlap consequences for this variation allele.
289 """
290 return self._overlap_consequences
292 @cached_property
293 def _overlap_consequences(self) -> list[OverlapConsequence]:
294 """Returns the list of overlap consequences for this variation allele.
296 Returns:
297 list[OverlapConsequence]: A list of overlap consequences for this variation allele.
298 """
299 feature_overlaps = self.get_all_featureoverlaps()
300 consequences = []
301 for feature_overlap in feature_overlaps:
302 consequences.extend(feature_overlap.overlap_consequences)
303 return consequences
305 def get_all_featureoverlaps(self) -> Sequence[FeatureOverlap]:
306 """Returns all feature overlaps for this variation allele.
308 Returns:
309 list[FeatureOverlap]: A list of all feature overlaps for this variation allele.
310 """
311 feature_overlaps = []
312 for tva in self.transcript_variation_alleles:
313 feature_overlaps.append(tva)
314 # Similarly, we would extend with regulatory_variation_alleles,
315 # motif_variation_alleles, etc. when they are implemented.
316 return feature_overlaps