Coverage for src/python/ensembl/vep/annotators/consequence/facts/sequence.py: 98%

171 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"""Facts derived from allele, codon, CDS, and peptide sequences. 

15 

16Internal codon and peptide facts perform sequence editing and translation. Public facts reuse 

17those values or perform length arithmetic. 

18""" 

19 

20from __future__ import annotations 

21 

22from ensembl.vep.annotators.consequence.facts.base import get_fact, register_fact 

23from ensembl.vep.common import CostTier 

24from ensembl.vep.annotators.consequence.facts.helper import ( 

25 get_codon_alleles, 

26 get_peptide_alleles, 

27 get_full_cds_peptide_alleles, 

28) 

29from ensembl.vep.annotators.consequence.context.fact import FactContext 

30from ensembl.vep.common.constants import EMPTY_ALLELE 

31from ensembl.vep.models.overlap import TranscriptVariationAllele 

32 

33__all__ = [ 

34 "alt_matches_ref_codon_edge", 

35 "alt_peptide_has_ter", 

36 "alt_peptide_is_ter", 

37 "alt_peptide_matches_ref_edge", 

38 "cds_length_change_inframe", 

39 "cds_start_lost", 

40 "cds_start_retained", 

41 "cds_stop_gain", 

42 "cds_stop_lost", 

43 "cds_stop_retained", 

44 "insertion_after_start", 

45 "insertion_before_start", 

46 "peptide_changed", 

47 "peptide_has_X", 

48 "peptide_same_length", 

49 "ref_peptide_has_ter", 

50 "ref_peptide_is_ter", 

51 "ref_peptide_startswith_ter", 

52] 

53 

54 

55def _is_empty_codon(codon: str) -> bool: 

56 """Return whether a codon window contains no bases.""" 

57 return codon in ("", EMPTY_ALLELE) 

58 

59 

60def _matches_codon_edge(container: str, contained: str) -> bool: 

61 r"""Return whether ``contained`` aligns to a codon-preserving edge of ``container``. 

62 

63 VEP's two-branch test (``VariationEffect::inframe_deletion``): the string match 

64 ``$container =~ /^\Q$contained\E/ || /\Q$contained\E$/``, then, failing that, 

65 ``trim_sequences`` on the pair and nothing left of ``contained`` with what remains of 

66 ``container`` a whole number of codons. An empty ``contained`` matches either edge already, 

67 as the Perl regex does. 

68 """ 

69 if _is_empty_codon(contained): 

70 return True 

71 if container.startswith(contained) or container.endswith(contained): 

72 return True 

73 

74 leading = 0 

75 while leading < len(container) and leading < len(contained) and container[leading] == contained[leading]: 

76 leading += 1 

77 remaining_container, remaining_contained = container[leading:], contained[leading:] 

78 

79 trailing = 0 

80 while ( 

81 trailing < len(remaining_container) 

82 and trailing < len(remaining_contained) 

83 and remaining_container[-1 - trailing] == remaining_contained[-1 - trailing] 

84 ): 

85 trailing += 1 

86 if trailing: 

87 remaining_container = remaining_container[:-trailing] 

88 remaining_contained = remaining_contained[:-trailing] 

89 return not remaining_contained and len(remaining_container) % 3 == 0 

90 

91 

92# -------------------------------------------------------------------------- 

93# Comparisons between only codon/peptide alleles variant overlaps. 

94# -------------------------------------------------------------------------- 

95 

96 

97@register_fact(CostTier.SEQUENCE) 

98def _codon_alleles(fact_context: FactContext[TranscriptVariationAllele]) -> tuple[str, str] | None: 

99 """Return reference and alternate codon windows around the variant. 

100 

101 The overlap cases its codons for display; every comparison here is on the bases alone. 

102 """ 

103 reference_codon = fact_context.overlap.reference_codon 

104 alternate_codon = fact_context.overlap.alternate_codon 

105 if reference_codon is None or alternate_codon is None: 

106 return None 

107 return reference_codon.upper(), alternate_codon.upper() 

108 

109 

110@register_fact(CostTier.SEQUENCE) 

111def _peptide_alleles(fact_context: FactContext[TranscriptVariationAllele]) -> tuple[str, str] | None: 

112 """Return peptides translated from the reference and alternate codon windows.""" 

113 reference_peptide = fact_context.overlap.reference_peptide 

114 alternate_peptide = fact_context.overlap.alternate_peptide 

115 if reference_peptide is None or alternate_peptide is None: 

116 return None 

117 return reference_peptide, alternate_peptide 

118 

119 

120@register_fact( 

121 CostTier.SEQUENCE, 

122 deps=("_codon_alleles",), 

123 requires=( 

124 "is_transcript", 

125 "overlap_feature", 

126 "overlap_cds", 

127 ), 

128) 

129def alt_matches_ref_codon_edge(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

130 """Return whether a deletion removes whole codons while preserving a window edge. 

131 

132 VEP's own test for an inframe deletion (``VariationEffect::inframe_deletion``): see 

133 ``_matches_codon_edge`` for its two branches. 

134 """ 

135 codons = get_codon_alleles(fact_context) 

136 if codons is None: 

137 return False 

138 reference_codon, alternate_codon = codons 

139 return _matches_codon_edge(reference_codon, alternate_codon) 

140 

141 

142@register_fact( 

143 CostTier.SEQUENCE, 

144 deps=("_peptide_alleles",), 

145 requires=( 

146 "is_transcript", 

147 "overlap_feature", 

148 "overlap_cds", 

149 "has_translation", 

150 ), 

151) 

152def alt_peptide_matches_ref_edge(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

153 """Return whether the alternate peptide preserves a reference-window edge. 

154 

155 VEP's test for an inframe insertion (``VariationEffect::inframe_insertion``), which it makes on 

156 the peptides rather than the codons: residues added at one end of the window leave the 

157 reference residues intact at the other. The alternate window is cut at its first stop first, so 

158 that an insertion which also introduces a stop is judged on what precedes it. 

159 """ 

160 peptides = get_peptide_alleles(fact_context) 

161 if peptides is None: 

162 return False 

163 reference_peptide, alternate_peptide = peptides 

164 if not reference_peptide: 

165 return True 

166 stop_index = alternate_peptide.find("*") 

167 if stop_index != -1: 

168 alternate_peptide = alternate_peptide[: stop_index + 1] 

169 return alternate_peptide.startswith(reference_peptide) or alternate_peptide.endswith(reference_peptide) 

170 

171 

172@register_fact( 

173 CostTier.SEQUENCE, 

174 deps=("_peptide_alleles",), 

175 requires=( 

176 "is_transcript", 

177 "overlap_feature", 

178 "overlap_cds", 

179 "has_translation", 

180 ), 

181) 

182def peptide_changed(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

183 """Return whether the reference and alternate peptide windows differ.""" 

184 peptides = get_peptide_alleles(fact_context) 

185 return peptides is not None and peptides[0] != peptides[1] 

186 

187 

188@register_fact( 

189 CostTier.SEQUENCE, 

190 deps=("_peptide_alleles",), 

191 requires=( 

192 "is_transcript", 

193 "overlap_feature", 

194 "overlap_cds", 

195 "has_translation", 

196 ), 

197) 

198def peptide_same_length(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

199 """Return whether the peptide windows have the same length.""" 

200 peptides = get_peptide_alleles(fact_context) 

201 return peptides is not None and len(peptides[0]) == len(peptides[1]) 

202 

203 

204@register_fact( 

205 CostTier.SEQUENCE, 

206 deps=("_peptide_alleles",), 

207 requires=( 

208 "is_transcript", 

209 "overlap_feature", 

210 "overlap_cds", 

211 "has_translation", 

212 ), 

213) 

214def alt_peptide_has_ter(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

215 """Return whether the alternate peptide window contains a stop codon.""" 

216 peptides = get_peptide_alleles(fact_context) 

217 return peptides is not None and "*" in peptides[1] 

218 

219 

220@register_fact( 

221 CostTier.SEQUENCE, 

222 deps=("_peptide_alleles",), 

223 requires=( 

224 "is_transcript", 

225 "overlap_feature", 

226 "overlap_cds", 

227 "has_translation", 

228 ), 

229) 

230def ref_peptide_has_ter(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

231 """Return whether the reference peptide window contains a stop codon.""" 

232 peptides = get_peptide_alleles(fact_context) 

233 return peptides is not None and "*" in peptides[0] 

234 

235 

236@register_fact( 

237 CostTier.SEQUENCE, 

238 deps=("_peptide_alleles",), 

239 requires=( 

240 "is_transcript", 

241 "overlap_feature", 

242 "overlap_cds", 

243 "has_translation", 

244 ), 

245) 

246def peptide_has_X(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

247 """Return whether either peptide window contains an ambiguous residue. 

248 

249 "X" comes from an unresolvable codon (incomplete, or an ambiguity code). 

250 """ 

251 peptides = get_peptide_alleles(fact_context) 

252 return peptides is not None and ("X" in peptides[0] or "X" in peptides[1]) 

253 

254 

255@register_fact( 

256 CostTier.SEQUENCE, 

257 deps=("_peptide_alleles",), 

258 requires=( 

259 "is_transcript", 

260 "overlap_feature", 

261 "overlap_cds", 

262 "has_translation", 

263 ), 

264) 

265def ref_peptide_is_ter(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

266 """Return whether the reference peptide is exactly one stop codon.""" 

267 peptides = get_peptide_alleles(fact_context) 

268 return peptides is not None and peptides[0] == "*" 

269 

270 

271@register_fact( 

272 CostTier.SEQUENCE, 

273 deps=("_peptide_alleles",), 

274 requires=( 

275 "is_transcript", 

276 "overlap_feature", 

277 "overlap_cds", 

278 "has_translation", 

279 ), 

280) 

281def alt_peptide_is_ter(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

282 """Return whether the alternate peptide is exactly one stop codon.""" 

283 peptides = get_peptide_alleles(fact_context) 

284 return peptides is not None and peptides[1] == "*" 

285 

286 

287@register_fact( 

288 CostTier.SEQUENCE, 

289 deps=("_peptide_alleles",), 

290 requires=( 

291 "is_transcript", 

292 "overlap_feature", 

293 "overlap_cds", 

294 "has_translation", 

295 ), 

296) 

297def ref_peptide_startswith_ter(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

298 """Return whether the reference peptide window begins with a stop codon.""" 

299 peptides = get_peptide_alleles(fact_context) 

300 return peptides is not None and peptides[0].startswith("*") 

301 

302 

303@register_fact( 

304 CostTier.SEQUENCE, 

305 deps=("_peptide_alleles",), 

306 requires=( 

307 "is_transcript", 

308 "overlap_feature", 

309 "overlap_cds", 

310 "has_translation", 

311 ), 

312) 

313def insertion_before_start(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

314 """Return whether an insertion occurs before and preserves the start codon. 

315 

316 Because variant overlaps start codon (verified by overlap_start_codon fact requirement) the reference 

317 peptide should include the start peptide. If the alternate peptide window ends with the reference peptide 

318 then it also include the start codon with inserted amino acids before it. 

319 

320 An empty reference peptide is excluded because ``str.endswith("")`` is trivially True for any string, 

321 which would make this fact vacuously True for every overlap. 

322 """ 

323 peptides = get_peptide_alleles(fact_context) 

324 if peptides is None: 

325 return False 

326 reference_peptide, alternate_peptide = peptides 

327 return bool(reference_peptide) and alternate_peptide.endswith(reference_peptide) 

328 

329 

330@register_fact( 

331 CostTier.SEQUENCE, 

332 deps=("_peptide_alleles",), 

333 requires=( 

334 "is_transcript", 

335 "overlap_feature", 

336 "overlap_cds", 

337 "has_translation", 

338 ), 

339) 

340def insertion_after_start(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

341 """Return whether an insertion occurs after and preserves the start codon.""" 

342 peptides = get_peptide_alleles(fact_context) 

343 if peptides is None: 

344 return False 

345 reference_peptide, alternate_peptide = peptides 

346 return bool(reference_peptide) and alternate_peptide.startswith(reference_peptide) 

347 

348 

349# -------------------------------------------------------------------------- 

350# Comparisons between full CDS/protein sequences. 

351# 

352# Unlike _codon_alleles/_peptide_alleles above, a few bases around the variant, the facts below need 

353# the real downstream sequence. For example, an indel elsewhere in the CDS that shifts the 

354# reading frame isn't visible in a narrow window. 

355# 

356# Deliberately not routed through codon_cache as that cache's key is the narrow codon window's genomic 

357# positions specifically (see its own module docstring on the "frame-vs-footprint failure family") 

358# -------------------------------------------------------------------------- 

359 

360 

361@register_fact(CostTier.TRANSCRIPT_SEQUENCE) 

362def _full_cds_peptide_alleles(fact_context: FactContext[TranscriptVariationAllele]) -> tuple[str, str] | None: 

363 """Return peptides translated from the complete reference and alternate CDS. 

364 

365 ``data/fact_costs.json`` (the opt-in measured-cost override, see facts/base.py) has no entry 

366 for this fact, so its declared ``CostTier.TRANSCRIPT_SEQUENCE`` applies whenever that override 

367 is enabled too -- not regenerated here since ``vep catalogue costs`` profiles against a live 

368 corpus and picking one is a judgement call outside this change's scope. 

369 """ 

370 reference = fact_context.overlap.reference_cds_peptide 

371 alternate = fact_context.overlap.alternate_cds_peptide 

372 if reference is None or alternate is None: 

373 return None 

374 return reference, alternate 

375 

376 

377@register_fact( 

378 CostTier.FREE, 

379 deps=("_full_cds_peptide_alleles",), 

380 requires=( 

381 "is_transcript", 

382 "overlap_feature", 

383 "overlap_cds", 

384 "has_translation", 

385 "overlap_start_codon", 

386 ), 

387) 

388def cds_start_lost(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

389 """Return whether the alternate CDS loses the start codon.""" 

390 peptides = get_full_cds_peptide_alleles(fact_context) 

391 if peptides is None: 

392 return False 

393 reference_peptide, alternate_peptide = peptides 

394 # We need slice here to avoid IndexError on empty string 

395 return reference_peptide[0:1] != alternate_peptide[0:1] 

396 

397 

398@register_fact( 

399 CostTier.FREE, 

400 deps=("_full_cds_peptide_alleles",), 

401 requires=( 

402 "is_transcript", 

403 "overlap_feature", 

404 "overlap_cds", 

405 "has_translation", 

406 ), 

407) 

408def cds_stop_lost(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

409 """Return whether the alternate CDS loses the stop codon. 

410 

411 Requires the alternate peptide to match the reference up to (but not including) the reference's own stop 

412 position, so a frameshift several codons upstream that happens to remove the stop incidentally doesn't 

413 get conflated with an edit that actually changes the stop codon itself. 

414 """ 

415 peptides = get_full_cds_peptide_alleles(fact_context) 

416 if peptides is None: 

417 return False 

418 reference_peptide, alternate_peptide = peptides 

419 reference_stop = reference_peptide.find("*") 

420 if reference_stop == -1: 

421 return False 

422 if alternate_peptide[:reference_stop] != reference_peptide[:reference_stop]: 

423 return False 

424 return len(alternate_peptide) <= reference_stop or alternate_peptide[reference_stop] != "*" 

425 

426 

427@register_fact( 

428 CostTier.FREE, 

429 deps=("_full_cds_peptide_alleles",), 

430 requires=( 

431 "is_transcript", 

432 "overlap_feature", 

433 "overlap_cds", 

434 "has_translation", 

435 "overlap_start_codon", 

436 ), 

437) 

438def cds_start_retained(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

439 """Return whether the alternate CDS retains the initiator methionine. 

440 

441 Computed from the peptides directly rather than as ``not cds_start_lost``. Negating a *guarded* 

442 fact is unsound: when a required atom is false, ``cds_start_lost`` short-circuits to False, and 

443 ``not False`` claims the start codon is retained for a variant that never touches it -- which 

444 is exactly what ``verify_requires`` catches by running this body unguarded. Deriving it here 

445 also returns False (not True) when the peptides are unavailable, matching ``cds_stop_retained``. 

446 Caching is unaffected: ``_full_cds_peptide_alleles`` is the memoised dep both facts read. 

447 """ 

448 

449 # Explicit guard here to enforce the design a required False mean the fact short-circuits to False; 

450 # otherwise, the fact would be True for a variant that never touches the start codon. 

451 if get_fact(fact_context, "overlap_start_codon") is False: 

452 return False 

453 

454 peptides = get_full_cds_peptide_alleles(fact_context) 

455 if peptides is None: 455 ↛ 456line 455 didn't jump to line 456 because the condition on line 455 was never true

456 return False 

457 reference_peptide, alternate_peptide = peptides 

458 # We need slice here to avoid IndexError on empty string 

459 return reference_peptide[0:1] == alternate_peptide[0:1] 

460 

461 

462@register_fact( 

463 CostTier.FREE, 

464 deps=("_full_cds_peptide_alleles",), 

465 requires=( 

466 "is_transcript", 

467 "overlap_feature", 

468 "overlap_cds", 

469 "has_translation", 

470 ), 

471) 

472def cds_stop_retained(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

473 """Return whether the alternate CDS retains the stop codon. 

474 

475 Requires stop at the exact same reading-frame position, with the same prefix leading up to it.""" 

476 

477 # Explicit guard here to enforce the design a required False mean the fact short-circuits to False; 

478 # otherwise, the fact would be True for a variant that never touches the stop codon. Except for a 

479 # unknown peptide (generally caused by frameshift) that may cause the stop codon to appear retained. 

480 # Because of composite fact we cannot add it to the requires list directly. 

481 if ( 

482 get_fact(fact_context, "overlap_stop_codon") is False 

483 and get_fact(fact_context, "peptide_has_X") is False 

484 ): 

485 return False 

486 

487 peptides = get_full_cds_peptide_alleles(fact_context) 

488 if peptides is None: 488 ↛ 489line 488 didn't jump to line 489 because the condition on line 488 was never true

489 return False 

490 reference_peptide, alternate_peptide = peptides 

491 reference_stop = reference_peptide.find("*") 

492 if reference_stop == -1: 

493 return False 

494 if alternate_peptide[:reference_stop] != reference_peptide[:reference_stop]: 

495 return False 

496 return len(alternate_peptide) > reference_stop and alternate_peptide[reference_stop] == "*" 

497 

498 

499@register_fact( 

500 CostTier.FREE, 

501 deps=("_full_cds_peptide_alleles",), 

502 requires=( 

503 "is_transcript", 

504 "overlap_feature", 

505 "overlap_cds", 

506 "has_translation", 

507 ), 

508) 

509def cds_stop_gain(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

510 """Return whether the alternate CDS introduces a premature stop codon.""" 

511 peptides = get_full_cds_peptide_alleles(fact_context) 

512 if peptides is None: 

513 return False 

514 reference_peptide, alternate_peptide = peptides 

515 reference_stop = reference_peptide.find("*") 

516 if reference_stop == -1: 

517 return False 

518 alternate_stop = alternate_peptide.find("*") 

519 return 0 <= alternate_stop < reference_stop 

520 

521 

522# -------------------------------------------------------------------------- 

523# Sequence length arithmetic. 

524# -------------------------------------------------------------------------- 

525 

526 

527@register_fact( 

528 CostTier.MAPPING, 

529 requires=( 

530 "is_transcript", 

531 "overlap_feature", 

532 "overlap_cds", 

533 "has_translation", 

534 ), 

535) 

536def cds_length_change_inframe(fact_context: FactContext[TranscriptVariationAllele]) -> bool: 

537 """Return whether the coding-length change is in frame. 

538 

539 False when the variant does not overlap the CDS. There is then no coding length change to be in 

540 frame, and reporting True would contradict this fact's own ``requires``. 

541 """ 

542 length_change = fact_context.overlap.cds_length_change 

543 if length_change is None: 

544 return False 

545 return length_change % 3 == 0