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

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.""" 

15 

16from __future__ import annotations 

17 

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 

25 

26from ensembl.vep.common.enums import Strand, ClassSOTerm 

27from ensembl.vep.common.constants import CLASS_SO_TERM_ABBRV_TO_ENUM, EMPTY_ALLELE 

28 

29logger = logging.getLogger(__name__) 

30 

31T = TypeVar("T") 

32 

33 

34def is_resolved(instance: object, name: str) -> bool: 

35 """Return whether a slot-backed cached property is already resolved without triggering computation. 

36 

37 Args: 

38 instance (object): Object that owns the cached property. 

39 name (str): Protected cached-property name (for example, "_cds"). 

40 

41 Returns: 

42 bool: True if the value is already present (seeded or previously computed), 

43 False if reading it would still trigger computation. 

44 

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__}") 

59 

60 

61def invalidate(instance: object, *invalidate_names: str) -> None: 

62 """Clear the named cached properties of a class object when the attributes are set. 

63 

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. 

68 

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. 

72 

73 Returns: 

74 None 

75 """ 

76 for name in invalidate_names: 

77 try: 

78 object.__delattr__(instance, name) 

79 except AttributeError: 

80 pass 

81 

82 

83def invalidates(*cached_names: str) -> Callable: 

84 """Return an attrs ``on_setattr`` hook that clears named cached properties. 

85 

86 Args: 

87 *cached_names (str): The names of the cached properties to invalidate. 

88 

89 Returns: 

90 Callable: An attrs on_setattr hook function. 

91 """ 

92 

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 ) 

98 

99 def hook(instance: object, _modified_attr: AttrsAttribute, new_value: T) -> T: 

100 invalidate(instance, *cached_names) 

101 

102 # attrs requires the hook to return the value 

103 return new_value 

104 

105 return hook 

106 

107 

108def resets_attrs(*attrs: tuple[str, Any]) -> Callable: 

109 """Return an attrs ``on_setattr`` hook that resets named attributes. 

110 

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 

115 

116 Returns: 

117 Callable: An on_setattr hook function. 

118 """ 

119 

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 

124 

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) 

136 

137 # attrs requires the hook to return the value on success 

138 return new_value 

139 

140 return hook 

141 

142 

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. 

155 

156 Trims matching bases from the start then end (or end then start if 

157 end_first=True), adjusting coordinates accordingly. 

158 

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. 

167 

168 Returns: 

169 Tuple of (new_ref, new_alt, new_start, new_end, changed). 

170 

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") 

176 

177 end = end or (start + (len(ref) - 1)) 

178 

179 changed = False 

180 

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 

187 

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 

193 

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 

200 

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 

206 

207 if empty_to_dash: 

208 ref = ref or EMPTY_ALLELE 

209 alt = alt or EMPTY_ALLELE 

210 

211 return (ref, alt, start, end, changed) 

212 

213 

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. 

225 

226 Trims matching bases from the start or end, adjusting coordinates accordingly. 

227 

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. 

235 

236 Returns: 

237 Tuple of (new_ref, new_alt, new_start, new_end, changed). 

238 """ 

239 

240 changed = False 

241 

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) 

245 

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 

264 

265 return (ref, alt, start, end, changed) 

266 

267 

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. 

279 

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. 

283 

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'. 

291 

292 Returns: 

293 Tuple of (shift_length, shifted_seq, new_start, new_end, changed). 

294 

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") 

300 

301 if seq == "": 

302 return (0, seq, start, end, False) 

303 

304 seq_len = len(seq) 

305 shift_length = 0 

306 

307 # Use deques for O(1) rotation instead of repeated string slicing 

308 seq_d = deque(seq) 

309 

310 changed = False 

311 

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 

317 

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 

322 

323 shift_length += 1 

324 start -= 1 

325 end -= 1 

326 

327 # Rotate allele: move last char to front 

328 seq_d.rotate(1) 

329 

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 

336 

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 

341 

342 shift_length += 1 

343 start += 1 

344 end += 1 

345 

346 # Rotate allele: move first char to end 

347 seq_d.rotate(-1) 

348 

349 changed = True 

350 

351 return (shift_length, "".join(seq_d), start, end, changed) 

352 

353 

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. 

356 

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. 

360 

361 Args: 

362 region (str): A region string in the format "seq_region_name[:start[-end]]". 

363 

364 Returns: 

365 tuple[str, int | None, int | None]: The name, start and end. 

366 

367 Raises: 

368 ValueError: If region is empty, or its coordinates are not positive integers. 

369 """ 

370 

371 if not region: 

372 raise ValueError("region must not be empty") 

373 

374 name, separator, coordinates = region.rpartition(":") 

375 if not separator: 

376 return region, None, None 

377 

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 

384 

385 if start < 1 or (end is not None and end < 1): 

386 raise ValueError("regions are 1-based and must be positive") 

387 

388 return name, start, end 

389 

390 

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. 

400 

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). 

406 

407 Returns: 

408 :A region string in the format "seq_region_name:start-end". 

409 """ 

410 

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") 

414 

415 return region 

416 

417 if seq_region_name is None: 

418 raise ValueError("region requires either region or seq_region_name") 

419 

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 

424 

425 if end is None: 

426 return f"{seq_region_name}:{start}" 

427 

428 if start < 1 or end < 1: 

429 raise ValueError("regions are 1-based and must be positive") 

430 

431 return f"{seq_region_name}:{start}-{end}" 

432 

433 

434def format_coords(start: int | None, end: int | None) -> str: 

435 """Return a coordinate range the way VEP prints one. 

436 

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}" 

449 

450 

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. 

454 

455 Args: 

456 allele_string: The allele string for the variation. 

457 ref_correct: Whether the first allele is known to be the reference. 

458 

459 Returns: 

460 The SO term string for the variation. 

461 """ 

462 # default to sequence_alteration 

463 so_term = ClassSOTerm.SEQUENCE_ALTERATION 

464 

465 # A/T, A/T/G 

466 if re.match(r"^[A-Z](/[A-Z])+$", allele_string): 

467 so_term = ClassSOTerm.SNV 

468 

469 # (CAG)8/(CAG)9 

470 elif re.search(r"\)\d+", allele_string): 

471 so_term = ClassSOTerm.TANDEM_REPEAT 

472 

473 else: 

474 alleles = allele_string.split("/") 

475 

476 if len(alleles) > 1: 

477 ref = alleles[0] 

478 alts = alleles[1:] 

479 

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 

484 

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 

488 

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 

493 

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 

498 

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 

503 

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 

511 

512 return so_term 

513 

514 

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. 

517 

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. 

523 

524 Args: 

525 allele_string: Symbolic alternate allele or breakend string. 

526 svtype: Optional structural variant type from VCF INFO/SVTYPE. 

527 

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() 

535 

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() 

541 

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 

571 

572 return CLASS_SO_TERM_ABBRV_TO_ENUM.get(abbreviation.upper()) 

573 

574 

575def reverse_complement(sequence: str) -> str: 

576 """Return the reverse complement of a nucleotide sequence. 

577 

578 Args: 

579 sequence (str): The sequence to reverse complement. 

580 

581 Returns: 

582 The reverse complement of the sequence. 

583 """ 

584 

585 translation_table = str.maketrans("ACGTNacgtn", "TGCANtgcan") 

586 return sequence.translate(translation_table)[::-1] 

587 

588 

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. 

591 

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. 

596 

597 Records go to stderr, as in Perl VEP, so a verb that prints its report to stdout stays 

598 redirectable. 

599 

600 The level is also the tracing switch -- a derivation trace is recorded only when the calling 

601 strategy's logger is at DEBUG. 

602 

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() 

613 

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)