Coverage for src/python/ensembl/vep/common/methods.py: 97%
244 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"""Common functions."""
16from __future__ import annotations
18from collections import deque
19import logging
20import os
21import sys
22import re
23from typing import Any, Callable, Literal, TypeVar
24from attrs import Attribute as AttrsAttribute
26from ensembl.vep.common.enums import Strand, ClassSOTerm
27from ensembl.vep.common.constants import CLASS_SO_TERM_ABBRV_TO_ENUM, EMPTY_ALLELE
29logger = logging.getLogger(__name__)
31T = TypeVar("T")
34def is_resolved(instance: object, name: str) -> bool:
35 """Return whether a slot-backed cached property is already resolved without triggering computation.
37 Args:
38 instance (object): Object that owns the cached property.
39 name (str): Protected cached-property name (for example, "_cds").
41 Returns:
42 bool: True if the value is already present (seeded or previously computed),
43 False if reading it would still trigger computation.
45 Raises:
46 AttributeError: If name is not a descriptor on the instance type hierarchy.
47 """
48 for cls in type(instance).__mro__:
49 descriptor = cls.__dict__.get(name)
50 if descriptor is not None and hasattr(descriptor, "__get__"):
51 try:
52 # Use descriptor.__get__ directly: normal access (including getattr)
53 # would invoke __getattr__ and compute/cache the value on a miss.
54 descriptor.__get__(instance, type(instance)) # pylint: disable=unnecessary-dunder-call
55 return True
56 except AttributeError:
57 return False
58 raise AttributeError(f"{name!r} is not a descriptor on {type(instance).__name__}")
61def invalidate(instance: object, *invalidate_names: str) -> None:
62 """Clear the named cached properties of a class object when the attributes are set.
64 Deleting an unset cached property raises AttributeError almost every time (a freshly built
65 object has nothing cached yet), so this uses ``try/except`` rather than
66 ``contextlib.suppress``: zero-cost when nothing is raised (Python 3.11+), and no context
67 manager allocated per name either way.
69 Args:
70 instance (object): The object whose cached properties should be cleared.
71 *invalidate_names (str): The names of the cached properties to invalidate.
73 Returns:
74 None
75 """
76 for name in invalidate_names:
77 try:
78 object.__delattr__(instance, name)
79 except AttributeError:
80 pass
83def invalidates(*cached_names: str) -> Callable:
84 """Return an attrs ``on_setattr`` hook that clears named cached properties.
86 Args:
87 *cached_names (str): The names of the cached properties to invalidate.
89 Returns:
90 Callable: An attrs on_setattr hook function.
91 """
93 for name in cached_names:
94 if not name.startswith("_"):
95 logger.debug(
96 f"Invalidation only works for protected attributes (starting with _), but got '{name}'"
97 )
99 def hook(instance: object, _modified_attr: AttrsAttribute, new_value: T) -> T:
100 invalidate(instance, *cached_names)
102 # attrs requires the hook to return the value
103 return new_value
105 return hook
108def resets_attrs(*attrs: tuple[str, Any]) -> Callable:
109 """Return an attrs ``on_setattr`` hook that resets named attributes.
111 Args:
112 *attrs: list of tuples (name, default_value) where
113 * `name` is the attribute name to reset
114 * `default_value` is the value to reset the attribute to on each call
116 Returns:
117 Callable: An on_setattr hook function.
118 """
120 def hook(instance: object, _modified_attr: AttrsAttribute, new_value: T) -> T:
121 # nothing to do if the value hasn't changed
122 if object.__getattribute__(instance, _modified_attr.name) == new_value:
123 return new_value
125 # Otherwise, reset the attributes defined in attrs
126 for attr_pair in attrs:
127 name = attr_pair[0]
128 default_value = attr_pair[1]
129 if not name.startswith("_"): 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true
130 logger.debug(
131 "reset_attrs should only be used for protected attributes (starting with _),"
132 f" but got '{name}'."
133 )
134 else:
135 object.__setattr__(instance, name, default_value)
137 # attrs requires the hook to return the value on success
138 return new_value
140 return hook
143def trim_sequences(
144 ref: str,
145 alt: str,
146 *,
147 start: int = 0,
148 end: int | None = None,
149 empty_to_dash: bool = False,
150 end_first: bool = False,
151 strand: Strand = Strand.FORWARD,
152) -> tuple[str, str, int, int, bool]:
153 """
154 Trim common sequence from a ref/alt allele pair to give minimal alleles.
156 Trims matching bases from the start then end (or end then start if
157 end_first=True), adjusting coordinates accordingly.
159 Args:
160 ref: Reference allele sequence.
161 alt: Alternate allele sequence.
162 start: Start coordinate (default 0).
163 end: End coordinate (default: start + len(ref) - 1).
164 empty_to_dash: If True, replace empty alleles with "-".
165 end_first: If True, trim from end before start.
166 strand: 1 for forward, -1 for reverse strand.
168 Returns:
169 Tuple of (new_ref, new_alt, new_start, new_end, changed).
171 Raises:
172 ValueError: If ref or alt is None.
173 """
174 if ref is None or alt is None:
175 raise ValueError("Missing reference or alternate sequence for trimming")
177 end = end or (start + (len(ref) - 1))
179 changed = False
181 if end_first:
182 # trim from right
183 ref, alt, start, end, right_changed = _trim_common_sequence(
184 ref, alt, start=start, end=end, trim_at="right", strand=strand
185 )
186 changed = right_changed
188 # trim from left
189 ref, alt, start, end, left_changed = _trim_common_sequence(
190 ref, alt, start=start, end=end, trim_at="left", strand=strand
191 )
192 changed = changed or left_changed
194 else:
195 # trim from left
196 ref, alt, start, end, left_changed = _trim_common_sequence(
197 ref, alt, start=start, end=end, trim_at="left", strand=strand
198 )
199 changed = left_changed
201 # trim from right
202 ref, alt, start, end, right_changed = _trim_common_sequence(
203 ref, alt, start=start, end=end, trim_at="right", strand=strand
204 )
205 changed = changed or right_changed
207 if empty_to_dash:
208 ref = ref or EMPTY_ALLELE
209 alt = alt or EMPTY_ALLELE
211 return (ref, alt, start, end, changed)
214def _trim_common_sequence(
215 ref: str,
216 alt: str,
217 *,
218 start: int = 0,
219 end: int,
220 trim_at: Literal["left", "right"],
221 strand: Strand = Strand.FORWARD,
222) -> tuple[str, str, int, int, bool]:
223 """
224 Trim common sequence from start or end of a ref/alt allele pair.
226 Trims matching bases from the start or end, adjusting coordinates accordingly.
228 Args:
229 ref: Reference allele sequence.
230 alt: Alternate allele sequence.
231 start: Start coordinate (default 0).
232 end: End coordinate (default: start + len(ref) - 1).
233 trim_at: What side to trim from: 'left' or 'right'.
234 strand: 1 for forward, -1 for reverse strand.
236 Returns:
237 Tuple of (new_ref, new_alt, new_start, new_end, changed).
238 """
240 changed = False
242 if strand == Strand.UNKNOWN:
243 logger.warning("Strand is unknown, cannot trim alleles with confidence. Returning untrimmed alleles.")
244 return (ref, alt, start, end, changed)
246 if trim_at == "left":
247 while ref and alt and ref[0] == alt[0]:
248 ref = ref[1:]
249 alt = alt[1:]
250 if strand == Strand.REVERSE:
251 end -= 1
252 else:
253 start += 1
254 changed = True
255 else:
256 while ref and alt and ref[-1] == alt[-1]:
257 ref = ref[:-1]
258 alt = alt[:-1]
259 if strand == Strand.REVERSE:
260 start += 1
261 else:
262 end -= 1
263 changed = True
265 return (ref, alt, start, end, changed)
268def shift_sequence(
269 seq: str,
270 *,
271 post_seq: str,
272 pre_seq: str,
273 start: int,
274 end: int,
275 reverse: bool = False,
276) -> tuple[int, str, int, int, bool]:
277 """
278 Calculate the maximum possible 3' (or 5') shift for an allele sequence.
280 Slides the allele along the flanking sequence as long as the
281 leading/trailing base matches the next flanking base, updating
282 coordinates and the HGVS allele string accordingly.
284 Args:
285 seq: The allele sequence to shift.
286 post_seq: 3' flanking sequence (downstream).
287 pre_seq: 5' flanking sequence (upstream).
288 start: Variant start coordinate.
289 end: Variant end coordinate.
290 reverse: If True, shift in the 5' direction; otherwise 3'.
292 Returns:
293 Tuple of (shift_length, shifted_seq, new_start, new_end, changed).
295 Raises:
296 ValueError: If seq, post_seq, or pre_seq is None.
297 """
298 if seq is None or post_seq is None or pre_seq is None:
299 raise ValueError("Missing sequence to shift")
301 if seq == "":
302 return (0, seq, start, end, False)
304 seq_len = len(seq)
305 shift_length = 0
307 # Use deques for O(1) rotation instead of repeated string slicing
308 seq_d = deque(seq)
310 changed = False
312 if reverse:
313 pre_len = len(pre_seq)
314 loop_limit = pre_len - seq_len + 1
315 if loop_limit < 0: 315 ↛ 316line 315 didn't jump to line 316 because the condition on line 315 was never true
316 loop_limit = pre_len
318 for n in range(1, loop_limit + 1):
319 # Compare last char of allele with upstream flanking base
320 if seq_d[-1] != pre_seq[pre_len - n]: 320 ↛ 321line 320 didn't jump to line 321 because the condition on line 320 was never true
321 break
323 shift_length += 1
324 start -= 1
325 end -= 1
327 # Rotate allele: move last char to front
328 seq_d.rotate(1)
330 changed = True
331 else:
332 post_len = len(post_seq)
333 loop_limit = post_len - seq_len + 1
334 if loop_limit < 0:
335 loop_limit = post_len
337 for n in range(0, loop_limit):
338 # Compare first char of allele with downstream flanking base
339 if seq_d[0] != post_seq[n]:
340 break
342 shift_length += 1
343 start += 1
344 end += 1
346 # Rotate allele: move first char to end
347 seq_d.rotate(-1)
349 changed = True
351 return (shift_length, "".join(seq_d), start, end, changed)
354def parse_region_string(region: str) -> tuple[str, int | None, int | None]:
355 """Split a region string into its sequence-region name and optional bounds.
357 The inverse of format_region_string: "1:100-200" -> ("1", 100, 200), "1:100" -> ("1", 100,
358 None), "1" -> ("1", None, None). A name may itself contain ":" (as HLA contigs do), so only
359 the last ":" separates the coordinates, and only when what follows parses as bounds.
361 Args:
362 region (str): A region string in the format "seq_region_name[:start[-end]]".
364 Returns:
365 tuple[str, int | None, int | None]: The name, start and end.
367 Raises:
368 ValueError: If region is empty, or its coordinates are not positive integers.
369 """
371 if not region:
372 raise ValueError("region must not be empty")
374 name, separator, coordinates = region.rpartition(":")
375 if not separator:
376 return region, None, None
378 start_text, _, end_text = coordinates.partition("-")
379 try:
380 start = int(start_text)
381 end = int(end_text) if end_text else None
382 except ValueError as invalid:
383 raise ValueError(f"region coordinates must be integers: {region!r}") from invalid
385 if start < 1 or (end is not None and end < 1):
386 raise ValueError("regions are 1-based and must be positive")
388 return name, start, end
391def format_region_string(
392 region: str | None = None,
393 *,
394 seq_region_name: str | None = None,
395 start: int | None = None,
396 end: int | None = None,
397) -> str:
398 """Format a region string into "seq_region_name:start-end"
399 from either an existing region or seq_region_name/start/end values.
401 Args:
402 region: A region string in the format "seq_region_name:start-end".
403 seq_region_name: Sequence ID (e.g. chromosome name).
404 start: Start coordinate (1-based).
405 end: End coordinate (1-based).
407 Returns:
408 :A region string in the format "seq_region_name:start-end".
409 """
411 if region is not None:
412 if any(value is not None for value in (seq_region_name, start, end)):
413 raise ValueError("pass either region or seq_region_name/start/end, not both")
415 return region
417 if seq_region_name is None:
418 raise ValueError("region requires either region or seq_region_name")
420 if start is None:
421 if end is not None:
422 raise ValueError("end coordinate provided without start coordinate")
423 return seq_region_name
425 if end is None:
426 return f"{seq_region_name}:{start}"
428 if start < 1 or end < 1:
429 raise ValueError("regions are 1-based and must be positive")
431 return f"{seq_region_name}:{start}-{end}"
434def format_coords(start: int | None, end: int | None) -> str:
435 """Return a coordinate range the way VEP prints one.
437 A single position when start and end agree, the lower bound first when they are reversed (an
438 insertion's ``end`` is ``start - 1``), and ``?`` for a missing bound.
439 """
440 if start is None:
441 return "-" if end is None else f"?-{end}"
442 if end is None:
443 return f"{start}-?"
444 if start > end:
445 return f"{end}-{start}"
446 if start == end:
447 return str(start)
448 return f"{start}-{end}"
451def infer_variant_so_term(allele_string: str, ref_correct: bool = False) -> ClassSOTerm | None:
452 """
453 Return the SO term for the class of the variation.
455 Args:
456 allele_string: The allele string for the variation.
457 ref_correct: Whether the first allele is known to be the reference.
459 Returns:
460 The SO term string for the variation.
461 """
462 # default to sequence_alteration
463 so_term = ClassSOTerm.SEQUENCE_ALTERATION
465 # A/T, A/T/G
466 if re.match(r"^[A-Z](/[A-Z])+$", allele_string):
467 so_term = ClassSOTerm.SNV
469 # (CAG)8/(CAG)9
470 elif re.search(r"\)\d+", allele_string):
471 so_term = ClassSOTerm.TANDEM_REPEAT
473 else:
474 alleles = allele_string.split("/")
476 if len(alleles) > 1:
477 ref = alleles[0]
478 alts = alleles[1:]
480 if ref == EMPTY_ALLELE:
481 if len(alts) == 1 and re.search(r"DEL", alts[0]): 481 ↛ 483line 481 didn't jump to line 483 because the condition on line 481 was never true
482 # -/(LARGEDELETION)
483 so_term = ClassSOTerm.DELETION if ref_correct else ClassSOTerm.INDEL
485 if not any(not re.match(r"^[A-Z]+$|INS", alt) for alt in alts): 485 ↛ 512line 485 didn't jump to line 512 because the condition on line 485 was always true
486 # -/ATT, -/(LARGEINSERTION)
487 so_term = ClassSOTerm.INSERTION if ref_correct else ClassSOTerm.INDEL
489 elif re.match(r"^[A-Z]+$", ref):
490 if not any(not re.match(r"^-$|DEL", alt) for alt in alts):
491 # A/-, A/(LARGEDELETION)
492 so_term = ClassSOTerm.DELETION if ref_correct else ClassSOTerm.INDEL
494 elif re.match(r"^[A-Z]+(/[A-Z]+)+$", allele_string):
495 # AA/TT => substitution, AA/TTTT => indel
496 same_size = all(len(alt) == len(ref) for alt in alts)
497 so_term = ClassSOTerm.SUBSTITUTION if same_size else ClassSOTerm.INDEL
499 elif re.search(r"DEL", ref):
500 if not any(alt != EMPTY_ALLELE for alt in alts): 500 ↛ 512line 500 didn't jump to line 512 because the condition on line 500 was always true
501 # (LARGEDELETION)/-, (2345 BP DELETION)/-
502 so_term = ClassSOTerm.DELETION if ref_correct else ClassSOTerm.INDEL
504 elif len(alleles) == 1: 504 ↛ 512line 504 didn't jump to line 512 because the condition on line 504 was always true
505 if re.search(r"INS", alleles[0]):
506 # (LARGEINSERTION)
507 so_term = ClassSOTerm.INSERTION if ref_correct else ClassSOTerm.INDEL
508 elif re.search(r"DEL", alleles[0]):
509 # (308 BP DELETION)
510 so_term = ClassSOTerm.DELETION if ref_correct else ClassSOTerm.INDEL
512 return so_term
515def infer_symbolic_variant_so_term(allele_string: str, svtype: str | None = None) -> ClassSOTerm | None:
516 """Infer the SO term for a symbolic structural variant.
518 This mirrors the symbolic variant normalization performed by Perl VEP's
519 ``get_SO_term``. A VCF-compliant symbolic allele takes precedence over
520 ``svtype`` so that subtype information in values such as
521 ``<INS:ME:ALU>`` is retained. ``svtype`` is used as a fallback for a
522 missing or non-standard allele.
524 Args:
525 allele_string: Symbolic alternate allele or breakend string.
526 svtype: Optional structural variant type from VCF INFO/SVTYPE.
528 Returns:
529 The inferred structural variant SO term, or ``None`` if the type is
530 unsupported.
531 """
532 raw_type = allele_string.strip()
533 if svtype and not re.match(r"^<?(?:DEL|INS|DUP|INV|CNV|CN=?[0-9]+)", raw_type, flags=re.IGNORECASE):
534 raw_type = svtype.strip()
536 # Normalize repeated variants, e.g. INS/INS or <INS>,<INS>.
537 parts = re.split(r"[/,]", raw_type)
538 normalized_parts = [part.strip().strip("<>").upper() for part in parts]
539 if normalized_parts and all(part == normalized_parts[0] for part in normalized_parts):
540 raw_type = parts[0].strip()
542 mobile_element_match = re.search(r"(INS|DEL):(ME):?([A-Z0-9]+)?", raw_type, flags=re.IGNORECASE)
543 if mobile_element_match:
544 variant_class = mobile_element_match.group(1).upper()
545 element = (mobile_element_match.group(3) or "ME").upper()
546 element = "LINE1" if element == "L1" else element
547 subtype = element if element in {"ALU", "HERV", "LINE1", "SVA"} else "ME"
548 abbreviation = f"{variant_class}_{subtype}"
549 elif re.search(r"DEL", raw_type, flags=re.IGNORECASE) and re.search(
550 r"DUP", raw_type, flags=re.IGNORECASE
551 ):
552 abbreviation = "CNV"
553 elif re.search(r"DUP:TANDEM", raw_type, flags=re.IGNORECASE):
554 abbreviation = "TDUP"
555 elif re.search(r"CNV:TR", raw_type, flags=re.IGNORECASE):
556 abbreviation = "TREP"
557 elif re.search(r"CN=?[0-9]", raw_type, flags=re.IGNORECASE):
558 abbreviation = "CNV"
559 if re.fullmatch(r"<?CN=?0>?", raw_type, flags=re.IGNORECASE):
560 abbreviation = "DEL"
561 elif re.fullmatch(r"<?CN=?2>?", raw_type, flags=re.IGNORECASE):
562 abbreviation = "DUP"
563 elif re.search(r"CNV", raw_type, flags=re.IGNORECASE):
564 abbreviation = "CNV"
565 elif re.search(r"[\[\]]|^\.|\.$", raw_type):
566 abbreviation = "BND"
567 elif raw_type.startswith("<") or raw_type.endswith(">"):
568 abbreviation = re.sub(r"[<>]", "", raw_type).split(":", maxsplit=1)[0]
569 else:
570 abbreviation = raw_type
572 return CLASS_SO_TERM_ABBRV_TO_ENUM.get(abbreviation.upper())
575def reverse_complement(sequence: str) -> str:
576 """Return the reverse complement of a nucleotide sequence.
578 Args:
579 sequence (str): The sequence to reverse complement.
581 Returns:
582 The reverse complement of the sequence.
583 """
585 translation_table = str.maketrans("ACGTNacgtn", "TGCANtgcan")
586 return sequence.translate(translation_table)[::-1]
589def setup_logging(level: str = "INFO", log_file: str | os.PathLike | None = None) -> None:
590 """Set up logging configuration. Call once, from the application entry point.
592 Configures the ``ensembl.vep`` logger rather than the root one, so importing this package does
593 not take over an embedding application's logging. Repeated calls replace the handlers rather
594 than stacking them. Propagation is left on: turning it off silently disables pytest's
595 ``caplog`` for the rest of the process.
597 Records go to stderr, as in Perl VEP, so a verb that prints its report to stdout stays
598 redirectable.
600 The level is also the tracing switch -- a derivation trace is recorded only when the calling
601 strategy's logger is at DEBUG.
603 Args:
604 level (str): The logging level to use (default: "INFO").
605 log_file (str | os.PathLike | None): File to append records to, in addition to stderr, or
606 None for stderr only.
607 """
608 package_logger = logging.getLogger("ensembl.vep")
609 package_logger.setLevel(getattr(logging, level.upper()))
610 for handler in list(package_logger.handlers):
611 package_logger.removeHandler(handler)
612 handler.close()
614 formatter = logging.Formatter(
615 fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%Y-%m-%dT%H:%M:%S"
616 )
617 handlers: list[logging.Handler] = [logging.StreamHandler(sys.stderr)]
618 if log_file is not None: 618 ↛ 619line 618 didn't jump to line 619 because the condition on line 618 was never true
619 handlers.append(logging.FileHandler(log_file))
620 for handler in handlers:
621 handler.setFormatter(formatter)
622 package_logger.addHandler(handler)