Coverage for src/python/ensembl/vep/output/factory/base.py: 86%

338 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"""Format-neutral annotated variants and their factory. 

15 

16The factory is a port of the format-independent half of Perl VEP's ``OutputFactory.pm``. A variation 

17first becomes a hash of what is known from its position alone (``variation_hash``). That hash is 

18copied and extended once per (allele, feature) overlap (``allele_hash``). The copies are then 

19filtered, picked or squashed as the options ask (``output_hashes``), and ``build_annotated_variant`` 

20hands them to ``AnnotatedVariant.build``, which detaches the variant's own fields. The snapshot is 

21the only thing that crosses a worker boundary and the only thing an output format sees. 

22 

23Only fields this model can actually supply are ever populated. A column VEP fills from data not 

24carried here yet -- HGVS, SIFT, frequencies, co-located variants -- stays empty rather than being 

25approximated, which is VEP's own convention for "not available". The *column layout* for a given 

26set of flags is VEP's, so a downstream tool reading the ``Format`` declaration finds what it 

27expects. 

28 

29Consequences reach an allele through ``VariationAllele.transcript_variation_alleles``. Assigning 

30that list invalidates the allele's aggregate, so assign each overlap's consequences first and 

31attach the overlaps afterwards. 

32""" 

33 

34from __future__ import annotations 

35 

36import re 

37from collections.abc import Iterable, Iterator, Sequence 

38from functools import cache 

39from typing import Any 

40 

41from attrs import define, field, frozen 

42 

43from ensembl.vep.annotators.consequence.rules.catalogue import load_consequence_definitions 

44from ensembl.vep.common.constants import EMPTY_ALLELE, UNKNOWN_VALUE 

45from ensembl.vep.common.methods import format_coords 

46from ensembl.vep.models.overlap import OverlapConsequence, TranscriptVariationAllele 

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

48from ensembl.vep.stats import RunSummary, RunSummaryCollector 

49 

50__all__ = [ 

51 "DEFAULT_PICK_ORDER", 

52 "DISTANCE_TERMS", 

53 "FLAG_FIELDS", 

54 "AlleleOverlap", 

55 "AnnotatedVariant", 

56 "AnnotatedVariantFactory", 

57 "AnnotatedVariants", 

58 "AnnotationRecord", 

59] 

60 

61AnnotationRecord = dict[str, object] 

62"""One VEP output hash, copied from a selected allele-feature annotation.""" 

63 

64 

65DEFAULT_PICK_ORDER = ( 

66 "mane_select", 

67 "mane_plus_clinical", 

68 "canonical", 

69 "appris", 

70 "tsl", 

71 "biotype", 

72 "ccds", 

73 "rank", 

74 "length", 

75 "ensembl", 

76 "refseq", 

77) 

78"""The order ``--pick`` weighs a transcript by, as VEP defaults it. A criterion this model has no 

79data for ties for every candidate and so defers to the next one -- exactly VEP's behaviour when 

80two candidates are equal on a criterion.""" 

81 

82DISTANCE_TERMS = frozenset({"upstream_gene_variant", "downstream_gene_variant"}) 

83"""The terms whose output carries a ``DISTANCE`` to the transcript.""" 

84 

85FLAG_FIELDS = ( 

86 ("allele_number", ("ALLELE_NUM",)), 

87 ("show_ref_allele", ("REF_ALLELE",)), 

88 ("flag_pick", ("PICK",)), 

89 ("flag_pick_allele", ("PICK",)), 

90 ("variant_class", ("VARIANT_CLASS",)), 

91 ("symbol", ("SYMBOL", "SYMBOL_SOURCE", "HGNC_ID")), 

92 ("biotype", ("BIOTYPE",)), 

93 ("numbers", ("EXON", "INTRON")), 

94) 

95"""Flag -> the output fields it adds, in VEP's order, for the flags this factory supports. 

96 

97The whole field list is declared even where only part of it can be filled (``SYMBOL_SOURCE``, 

98``HGNC_ID``), so the column layout matches VEP's for the same flags.""" 

99 

100_MISSING_RANK = 1000 

101_UNKNOWN_PICK_VALUE = 1 

102_TSL_PATTERN = re.compile(r"tsl(\d+)") 

103_APPRIS_PATTERN = re.compile(r"([A-Za-z]).+(\d+)") 

104_VERSIONED = re.compile(r"\.\d+$") 

105 

106 

107def _as_iterator(variants: Iterable[AnnotatedVariant]) -> Iterator[AnnotatedVariant]: 

108 """Return a single-pass iterator over annotated variants.""" 

109 return iter(variants) 

110 

111 

112@cache 

113def _intergenic_consequence() -> OverlapConsequence: 

114 """Return ``intergenic_variant`` as the catalogue defines it: the term for an allele with no overlap.""" 

115 for definition in load_consequence_definitions(): 115 ↛ 124line 115 didn't jump to line 124 because the loop on line 115 didn't complete

116 if definition.term == "intergenic_variant": 

117 return OverlapConsequence( 

118 term=definition.term, 

119 accession=definition.accession, 

120 rank=definition.rank, 

121 tier=definition.tier, 

122 impact=definition.impact, 

123 ) 

124 raise LookupError("the catalogue defines no intergenic_variant term") 

125 

126 

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

128class AnnotatedVariant: 

129 """Format-neutral snapshot of one annotated variant. 

130 

131 Attributes: 

132 id (str | None): The uploaded or stable variant identifier. 

133 seq_region_name (str): The sequence-region name, as the input spelled it. 

134 start (int): The inclusive genomic start. 

135 end (int): The inclusive genomic end. 

136 strand (int): The genomic strand. 

137 allele_string (str): The reference and alternate alleles separated by ``/``. 

138 input_columns (tuple[str, ...]): The original input columns, when present. 

139 annotations (tuple[AnnotationRecord, ...]): Selected VEP output hashes. 

140 most_severe_consequence (str | None): The most severe emitted consequence term. 

141 variant_class (str | None): The Sequence Ontology class term. 

142 assembly_name (str | None): The assembly name, when known. 

143 skipped (bool): Whether annotation was skipped for this input variant. 

144 """ 

145 

146 id: str | None 

147 seq_region_name: str 

148 start: int 

149 end: int 

150 strand: int 

151 allele_string: str 

152 input_columns: tuple[str, ...] = () 

153 annotations: tuple[AnnotationRecord, ...] = () 

154 most_severe_consequence: str | None = None 

155 variant_class: str | None = None 

156 assembly_name: str | None = None 

157 skipped: bool = False 

158 

159 @classmethod 

160 def build( 

161 cls, 

162 variation: Variation, 

163 record_columns: Sequence[str] | None = None, 

164 *, 

165 annotations: tuple[AnnotationRecord, ...] = (), 

166 assembly_name: str | None = None, 

167 skipped: bool = False, 

168 ) -> AnnotatedVariant: 

169 """Return the snapshot of one variation, carrying records chosen elsewhere. 

170 

171 Which records a run writes is an output-format question, answered by the output factory; 

172 everything here is the variant's own. 

173 

174 Args: 

175 variation (Variation): The variation whose annotation is complete. 

176 record_columns (Sequence[str] | None): Original input columns, when available. 

177 annotations (tuple[AnnotationRecord, ...]): The selected output hashes. 

178 assembly_name (str | None): Assembly name to expose in structured output. 

179 skipped (bool): Whether sources could not annotate this variation. 

180 

181 Returns: 

182 AnnotatedVariant: The detached snapshot. 

183 """ 

184 uploaded_locus = variation.uploaded_locus 

185 uploaded_name = uploaded_locus.seq_region_name if uploaded_locus is not None else None 

186 sequence_region_name = uploaded_name or UNKNOWN_VALUE 

187 class_term = variation.class_so_term 

188 most_severe = None if skipped else variation.most_severe_consequence 

189 most_severe_term = most_severe.term if most_severe is not None else None 

190 if most_severe_term is None and annotations: 

191 # A term the model reports only inside the records, such as one a flag squashed. 

192 first_terms = annotations[0].get("Consequence") 

193 if isinstance(first_terms, (list, tuple)) and first_terms: 193 ↛ 196line 193 didn't jump to line 196 because the condition on line 193 was always true

194 most_severe_term = str(first_terms[0]) 

195 

196 return cls( 

197 id=variation.stable_id, 

198 seq_region_name=sequence_region_name, 

199 start=variation.start, 

200 end=variation.end, 

201 strand=int(variation.strand.value), 

202 allele_string=variation.allele_string or (class_term.value if class_term is not None else ""), 

203 input_columns=tuple(str(column) for column in record_columns or ()), 

204 annotations=annotations, 

205 most_severe_consequence=most_severe_term, 

206 variant_class=class_term.value if class_term is not None else None, 

207 assembly_name=assembly_name, 

208 skipped=skipped, 

209 ) 

210 

211 

212@define(kw_only=True, auto_attribs=True) 

213class AnnotatedVariants(Iterator[AnnotatedVariant]): 

214 """Closable annotation iterator with its completed run summary. 

215 

216 Attributes: 

217 variants (Iterable[AnnotatedVariant]): Ordered annotated variants. 

218 collector (RunSummaryCollector): Summary state updated as variants become available. 

219 """ 

220 

221 _iterator: Iterator[AnnotatedVariant] = field(alias="variants", converter=_as_iterator) 

222 _collector: RunSummaryCollector = field(alias="collector", repr=False) 

223 _completed: bool = field(default=False, init=False) 

224 _closed: bool = field(default=False, init=False) 

225 _variant_count: int = field(default=0, init=False) 

226 

227 def __iter__(self) -> AnnotatedVariants: 

228 """Return this single-pass annotation stream.""" 

229 return self 

230 

231 def __next__(self) -> AnnotatedVariant: 

232 """Return the next annotated variant in input order.""" 

233 if self._closed: 

234 raise StopIteration 

235 try: 

236 variant = next(self._iterator) 

237 except StopIteration: 

238 self._completed = True 

239 self.close() 

240 raise 

241 self._variant_count += 1 

242 return variant 

243 

244 def __enter__(self) -> AnnotatedVariants: 

245 """Return this stream for bounded consumption.""" 

246 return self 

247 

248 def __exit__(self, *_error: Any) -> None: 

249 """Close worker resources when consumption stops.""" 

250 self.close() 

251 

252 @property 

253 def completed(self) -> bool: 

254 """Return whether every input variant has been consumed.""" 

255 return self._completed 

256 

257 @property 

258 def variant_count(self) -> int: 

259 """Return the number of variants yielded to the consumer.""" 

260 return self._variant_count 

261 

262 @property 

263 def collector(self) -> RunSummaryCollector: 

264 """Return the collector after complete consumption. 

265 

266 Raises: 

267 RuntimeError: If the stream has not been exhausted. 

268 """ 

269 if not self._completed: 

270 raise RuntimeError("the run summary is available after the annotation stream is exhausted") 

271 return self._collector 

272 

273 @property 

274 def summary(self) -> RunSummary: 

275 """Return the final summary after complete consumption. 

276 

277 Raises: 

278 RuntimeError: If the stream has not been exhausted. 

279 """ 

280 if not self._completed: 

281 raise RuntimeError("the run summary is available after the annotation stream is exhausted") 

282 return self._collector.finish() 

283 

284 def close(self) -> None: 

285 """Release resources held by the underlying annotation iterator.""" 

286 if self._closed: 

287 return 

288 close = getattr(self._iterator, "close", None) 

289 if close is not None: 

290 close() 

291 self._closed = True 

292 

293 

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

295class AlleleOverlap: 

296 """One allele of a variation against one feature, with the consequences it was assigned. 

297 

298 Attributes: 

299 allele_number (int): The allele's 1-based position among the variation's alternates. 

300 allele (VariationAllele): The allele. 

301 overlap (TranscriptVariationAllele | None): The feature overlap, or None for an allele that 

302 overlaps nothing -- which VEP reports as intergenic. 

303 consequences (tuple[OverlapConsequence, ...]): The consequences, most severe first. 

304 """ 

305 

306 allele_number: int 

307 allele: VariationAllele 

308 overlap: TranscriptVariationAllele | None 

309 consequences: tuple[OverlapConsequence, ...] 

310 

311 @property 

312 def allele_seq(self) -> str: 

313 """Return the allele as VEP writes it, using ``-`` when empty.""" 

314 return self.allele.alternate_allele or EMPTY_ALLELE 

315 

316 

317@define(kw_only=True, auto_attribs=True) 

318class AnnotatedVariantFactory: # pylint: disable=too-many-instance-attributes 

319 """Factory for detached annotated-variant snapshots. 

320 

321 Attributes: 

322 most_severe (bool): One record per variation, carrying only its most severe term. 

323 summary (bool): One record per variation, carrying every distinct term, most severe first. 

324 pick (bool): Keep only the single best (allele, feature) per variation. 

325 pick_allele (bool): Keep the best feature per allele. 

326 flag_pick (bool): Keep everything, and mark the single best with ``PICK``. 

327 flag_pick_allele (bool): Keep everything, and mark the best per allele with ``PICK``. 

328 pick_order (tuple[str, ...]): The criteria the picking flags weigh, in order. 

329 no_intergenic (bool): Write nothing for an allele that overlaps no feature. 

330 variant_class (bool): Add ``VARIANT_CLASS``. 

331 symbol (bool): Add the gene symbol. 

332 biotype (bool): Add the transcript biotype. 

333 numbers (bool): Add exon and intron numbers. 

334 allele_number (bool): Add ``ALLELE_NUM``. 

335 show_ref_allele (bool): Add ``REF_ALLELE``. 

336 transcript_version (bool): Append the version to transcript identifiers. 

337 gene_version (bool): Append the version to gene identifiers. 

338 """ 

339 

340 most_severe: bool = field(default=False) 

341 summary: bool = field(default=False) 

342 pick: bool = field(default=False) 

343 pick_allele: bool = field(default=False) 

344 flag_pick: bool = field(default=False) 

345 flag_pick_allele: bool = field(default=False) 

346 pick_order: tuple[str, ...] = field(default=DEFAULT_PICK_ORDER) 

347 no_intergenic: bool = field(default=False) 

348 variant_class: bool = field(default=False) 

349 symbol: bool = field(default=False) 

350 biotype: bool = field(default=False) 

351 numbers: bool = field(default=False) 

352 allele_number: bool = field(default=False) 

353 show_ref_allele: bool = field(default=False) 

354 transcript_version: bool = field(default=False) 

355 gene_version: bool = field(default=False) 

356 

357 def flag_fields(self) -> list[str]: 

358 """Return the output fields the enabled flags add, in order and without repeats.""" 

359 fields: list[str] = [] 

360 for flag, names in FLAG_FIELDS: 

361 if not getattr(self, flag): 

362 continue 

363 for name in names: 

364 if name not in fields: 364 ↛ 363line 364 didn't jump to line 363 because the condition on line 364 was always true

365 fields.append(name) 

366 return fields 

367 

368 def output_hashes( 

369 self, variation: Variation, record_columns: Sequence[str] | None = None 

370 ) -> list[dict[str, object]]: 

371 """Return the output records of one variation, filtered and picked as the flags ask. 

372 

373 Args: 

374 variation (Variation): The variation, its alleles' overlaps carrying consequences. 

375 record_columns (Sequence[str] | None): The original VCF columns, if it came from one. 

376 

377 Returns: 

378 list[dict[str, object]]: One hash per written (allele, feature), or a single squashed 

379 hash under ``most_severe``/``summary``. Empty under ``no_intergenic`` for a 

380 variation that overlaps nothing. 

381 """ 

382 variation_fields = self.variation_hash(variation, record_columns) 

383 overlaps = self.allele_overlaps(variation) 

384 if not overlaps: 

385 return [] 

386 if self.summary or self.most_severe: 

387 return [self._summary_only(variation_fields, overlaps)] 

388 

389 selected, picked = self._filter(overlaps) 

390 hashes = [] 

391 for entry in selected: 

392 output_hash = dict(variation_fields) 

393 self.allele_hash(output_hash, entry) 

394 if any(entry is chosen for chosen in picked): 

395 output_hash["PICK"] = 1 

396 hashes.append(output_hash) 

397 return hashes 

398 

399 def build_annotated_variant( 

400 self, 

401 variation: Variation, 

402 record_columns: Sequence[str] | None = None, 

403 *, 

404 assembly_name: str | None = None, 

405 skipped: bool = False, 

406 ) -> AnnotatedVariant: 

407 """Detach one annotated variation, carrying the records the flags select. 

408 

409 Args: 

410 variation (Variation): The variation whose annotations are complete. 

411 record_columns (Sequence[str] | None): Original input columns, when available. 

412 assembly_name (str | None): Assembly name to expose in structured output. 

413 skipped (bool): Whether sources could not annotate this variation. 

414 

415 Returns: 

416 AnnotatedVariant: A serialisable snapshot for stream and file factories. 

417 """ 

418 annotations = () if skipped else tuple(self.output_hashes(variation, record_columns)) 

419 return AnnotatedVariant.build( 

420 variation, 

421 record_columns, 

422 annotations=annotations, 

423 assembly_name=assembly_name, 

424 skipped=skipped, 

425 ) 

426 

427 def variation_hash( 

428 self, variation: Variation, record_columns: Sequence[str] | None = None 

429 ) -> dict[str, object]: 

430 """Return what is known about a variation from its position alone.""" 

431 uploaded_locus = variation.uploaded_locus 

432 uploaded_name = uploaded_locus.seq_region_name if uploaded_locus is not None else None 

433 chromosome = uploaded_name or UNKNOWN_VALUE 

434 class_term = variation.class_so_term 

435 alleles = variation.allele_string or (class_term.value if class_term is not None else "") 

436 positional_name = f"{chromosome}_{variation.start}_{alleles}" 

437 

438 name = variation.stable_id 

439 if name and name not in {".", positional_name}: 

440 uploaded = name 

441 elif record_columns is not None and len(record_columns) >= 5: 441 ↛ 451line 441 didn't jump to line 451 because the condition on line 441 was always true

442 reference, alternates = record_columns[3], record_columns[4].replace(",", "/") 

443 uploaded = "_".join( 

444 ( 

445 record_columns[0], 

446 str(int(record_columns[1])), 

447 f"{reference}/{alternates}" if alternates else reference, 

448 ) 

449 ) 

450 else: 

451 uploaded = positional_name 

452 

453 fields: dict[str, object] = { 

454 "Uploaded_variation": uploaded, 

455 "Location": f"{chromosome}:{format_coords(variation.start, variation.end)}", 

456 } 

457 if self.variant_class and class_term is not None: 

458 fields["VARIANT_CLASS"] = class_term.value 

459 return fields 

460 

461 def allele_overlaps(self, variation: Variation) -> list[AlleleOverlap]: 

462 """Return every (allele, feature) of a variation, grouped by feature. 

463 

464 Grouped by feature and then in allele order, as VEP groups them. An allele with no overlap 

465 yields one intergenic entry, unless ``no_intergenic`` is set. 

466 """ 

467 order: list[str] = [] 

468 by_feature: dict[str, list[AlleleOverlap]] = {} 

469 intergenic: list[AlleleOverlap] = [] 

470 for index, allele in enumerate(variation.variation_alleles): 

471 overlaps = allele.transcript_variation_alleles 

472 if not overlaps: 

473 if not self.no_intergenic: 

474 intergenic.append( 

475 AlleleOverlap( 

476 allele_number=index + 1, 

477 allele=allele, 

478 overlap=None, 

479 consequences=(_intergenic_consequence(),), 

480 ) 

481 ) 

482 continue 

483 for overlap in overlaps: 

484 key = overlap.feature.stable_id 

485 if key not in by_feature: 

486 by_feature[key] = [] 

487 order.append(key) 

488 consequences = tuple(sorted(overlap.overlap_consequences, key=lambda item: item.rank)) 

489 by_feature[key].append( 

490 AlleleOverlap( 

491 allele_number=index + 1, allele=allele, overlap=overlap, consequences=consequences 

492 ) 

493 ) 

494 grouped = [entry for key in order for entry in by_feature[key]] 

495 return grouped + intergenic 

496 

497 def allele_hash(self, output_hash: dict[str, object], entry: AlleleOverlap) -> None: 

498 """Extend a copy of the variation's hash with one (allele, feature)'s fields, in place.""" 

499 output_hash["Allele"] = entry.allele_seq 

500 output_hash["Consequence"] = [consequence.term for consequence in entry.consequences] 

501 if entry.consequences and entry.consequences[0].impact is not None: 501 ↛ 503line 501 didn't jump to line 503 because the condition on line 501 was always true

502 output_hash["IMPACT"] = entry.consequences[0].impact.value 

503 if self.allele_number: 

504 output_hash["ALLELE_NUM"] = entry.allele_number 

505 if self.show_ref_allele: 505 ↛ 506line 505 didn't jump to line 506 because the condition on line 505 was never true

506 output_hash["REF_ALLELE"] = entry.allele.reference_allele or EMPTY_ALLELE 

507 if entry.overlap is not None: 

508 self._transcript_fields(output_hash, entry) 

509 

510 def _transcript_fields(self, output_hash: dict[str, object], entry: AlleleOverlap) -> None: 

511 """Add what a transcript overlap contributes.""" 

512 overlap = entry.overlap 

513 assert overlap is not None 

514 transcript = overlap.feature 

515 gene = transcript.gene 

516 

517 output_hash["Feature_type"] = "Transcript" 

518 feature = transcript.stable_id 

519 if self.transcript_version and transcript.version and not _VERSIONED.search(feature): 519 ↛ 520line 519 didn't jump to line 520 because the condition on line 519 was never true

520 feature = f"{feature}.{transcript.version}" 

521 output_hash["Feature"] = feature 

522 if gene is not None: 

523 gene_id = gene.stable_id 

524 if self.gene_version and gene.version and not _VERSIONED.search(gene_id): 524 ↛ 525line 524 didn't jump to line 525 because the condition on line 524 was never true

525 gene_id = f"{gene_id}.{gene.version}" 

526 output_hash["Gene"] = gene_id 

527 output_hash["STRAND"] = int(transcript.strand.value) 

528 

529 if self.numbers: 529 ↛ 530line 529 didn't jump to line 530 because the condition on line 529 was never true

530 exon_number = getattr(overlap, "exon_number", None) 

531 if exon_number: 

532 output_hash["EXON"] = f"{exon_number}/{len(transcript.spliced_exons)}" 

533 intron_number = getattr(overlap, "intron_number", None) 

534 if intron_number: 

535 output_hash["INTRON"] = f"{intron_number}/{len(transcript.introns)}" 

536 

537 if DISTANCE_TERMS.intersection(consequence.term for consequence in entry.consequences): 

538 distance = getattr(overlap, "distance_to_transcript", None) 

539 if distance is not None: 539 ↛ 540line 539 didn't jump to line 540 because the condition on line 539 was never true

540 output_hash["DISTANCE"] = distance 

541 

542 if self.symbol and gene is not None and gene.symbol not in (None, EMPTY_ALLELE): 542 ↛ 543line 542 didn't jump to line 543 because the condition on line 542 was never true

543 output_hash["SYMBOL"] = gene.symbol 

544 if self.biotype: 

545 # This model may carry the biotype on the gene only; VEP reads the transcript's. 

546 biotype = transcript.biotype or (gene.biotype if gene is not None else None) 

547 if biotype: 547 ↛ 550line 547 didn't jump to line 550 because the condition on line 547 was always true

548 output_hash["BIOTYPE"] = biotype 

549 

550 self._position_fields(output_hash, overlap) 

551 

552 @staticmethod 

553 def _position_fields(output_hash: dict[str, object], overlap: TranscriptVariationAllele) -> None: 

554 """Add cDNA/CDS/protein positions, amino acids and codons, where the overlap has them. 

555 

556 A position is written only when the variant touches that sequence at all, as VEP writes it, 

557 and an end off the sequence prints as ``?``. Codons come already cased the way VEP writes 

558 them, the allele's own bases upper case. 

559 """ 

560 for column, position in ( 

561 ("cDNA_position", overlap.cdna_position), 

562 ("CDS_position", overlap.cds_position), 

563 ("Protein_position", overlap.protein_position), 

564 ): 

565 if position is not None: 

566 output_hash[column] = format_coords(*position) 

567 

568 if overlap.feature.translation is None: 

569 return 

570 reference_peptide, alternate_peptide = overlap.reference_peptide, overlap.alternate_peptide 

571 if reference_peptide is not None or alternate_peptide is not None: 

572 if reference_peptide == alternate_peptide: 

573 output_hash["Amino_acids"] = reference_peptide 

574 else: 

575 output_hash["Amino_acids"] = ( 

576 f"{reference_peptide or EMPTY_ALLELE}/{alternate_peptide or EMPTY_ALLELE}" 

577 ) 

578 reference_codon, alternate_codon = overlap.reference_codon, overlap.alternate_codon 

579 if reference_codon is not None or alternate_codon is not None: 

580 output_hash["Codons"] = f"{reference_codon or EMPTY_ALLELE}/{alternate_codon or EMPTY_ALLELE}" 

581 

582 def _summary_only( 

583 self, variation_fields: dict[str, object], overlaps: Sequence[AlleleOverlap] 

584 ) -> dict[str, object]: 

585 """Squash every overlap's consequences into one record: all distinct terms, or the worst.""" 

586 output_hash = dict(variation_fields) 

587 consequences = sorted( 

588 (consequence for entry in overlaps for consequence in entry.consequences), 

589 key=lambda item: item.rank, 

590 ) 

591 if not consequences: 591 ↛ 592line 591 didn't jump to line 592 because the condition on line 591 was never true

592 return output_hash 

593 if self.summary: 

594 terms: list[str] = [] 

595 for consequence in consequences: 

596 if consequence.term not in terms: 

597 terms.append(consequence.term) 

598 output_hash["Consequence"] = terms 

599 else: 

600 output_hash["Consequence"] = [consequences[0].term] 

601 return output_hash 

602 

603 def _filter(self, overlaps: list[AlleleOverlap]) -> tuple[list[AlleleOverlap], list[AlleleOverlap]]: 

604 """Apply the picking flags, returning what to write and what to mark ``PICK``.""" 

605 if self.pick: 

606 return [self.pick_worst(overlaps)], [] 

607 if self.pick_allele: 607 ↛ 608line 607 didn't jump to line 608 because the condition on line 607 was never true

608 return [self.pick_worst(group) for group in _by_allele(overlaps)], [] 

609 if self.flag_pick: 

610 return overlaps, [self.pick_worst(overlaps)] 

611 if self.flag_pick_allele: 611 ↛ 612line 611 didn't jump to line 612 because the condition on line 611 was never true

612 return overlaps, [self.pick_worst(group) for group in _by_allele(overlaps)] 

613 return overlaps, [] 

614 

615 def pick_worst(self, overlaps: Sequence[AlleleOverlap]) -> AlleleOverlap: 

616 """Return the single overlap the pick order prefers. 

617 

618 A port of VEP's ``pick_worst_VariationFeatureOverlapAllele``: narrow the candidates one 

619 criterion at a time, keeping every candidate tied on it, until one remains; the first of 

620 any tie that survives every criterion wins. 

621 

622 Raises: 

623 ValueError: If there is nothing to pick from. 

624 """ 

625 if not overlaps: 625 ↛ 626line 625 didn't jump to line 626 because the condition on line 625 was never true

626 raise ValueError("nothing to pick from") 

627 candidates = list(overlaps) 

628 for criterion in self.pick_order: 628 ↛ 634line 628 didn't jump to line 634 because the loop on line 628 didn't complete

629 if len(candidates) == 1: 

630 break 

631 scores = [_pick_value(entry, criterion) for entry in candidates] 

632 best = min(scores) 

633 candidates = [entry for entry, score in zip(candidates, scores, strict=True) if score == best] 

634 return candidates[0] 

635 

636 

637def _by_allele(overlaps: Sequence[AlleleOverlap]) -> list[list[AlleleOverlap]]: 

638 """Group overlaps by allele, in allele order.""" 

639 groups: dict[str, list[AlleleOverlap]] = {} 

640 for entry in overlaps: 

641 groups.setdefault(entry.allele_seq, []).append(entry) 

642 return list(groups.values()) 

643 

644 

645def _attribute_values(entry: AlleleOverlap, name: str) -> list[str]: 

646 """Return the values of every transcript attribute with one name.""" 

647 if entry.overlap is None: 647 ↛ 648line 647 didn't jump to line 648 because the condition on line 647 was never true

648 return [] 

649 values = [] 

650 for attribute in entry.overlap.feature.attributes or []: 650 ↛ 651line 650 didn't jump to line 651 because the loop on line 650 never started

651 if attribute.name == name: 

652 values.append(str(attribute.value)) 

653 return values 

654 

655 

656# pylint: disable-next=too-many-return-statements 

657def _pick_value(entry: AlleleOverlap, criterion: str) -> int: 

658 """Return an overlap's score on one pick criterion; lower is preferred.""" 

659 if criterion == "rank": 

660 return entry.consequences[0].rank if entry.consequences else _MISSING_RANK 

661 if entry.overlap is None: 661 ↛ 662line 661 didn't jump to line 662 because the condition on line 661 was never true

662 return _UNKNOWN_PICK_VALUE if criterion not in {"tsl", "appris"} else 100 

663 transcript = entry.overlap.feature 

664 if criterion == "mane_select": 

665 return 0 if _attribute_values(entry, "MANE_Select") else 1 

666 if criterion == "mane_plus_clinical": 

667 return 0 if _attribute_values(entry, "MANE_Plus_Clinical") else 1 

668 if criterion == "biotype": 

669 biotype = transcript.biotype or (transcript.gene.biotype if transcript.gene is not None else None) 

670 return 0 if biotype == "protein_coding" else 1 

671 if criterion == "length": 

672 length = transcript.cds_length if transcript.translation is not None else transcript.length 

673 return -(length or 0) 

674 if criterion == "tsl": 

675 for value in _attribute_values(entry, "TSL"): 675 ↛ 676line 675 didn't jump to line 676 because the loop on line 675 never started

676 match = _TSL_PATTERN.search(value) 

677 if match and int(match.group(1)): 

678 return int(match.group(1)) 

679 return 100 

680 if criterion == "appris": 

681 for value in _attribute_values(entry, "appris"): 681 ↛ 682line 681 didn't jump to line 682 because the loop on line 681 never started

682 match = _APPRIS_PATTERN.search(value) 

683 if match: 

684 grade = int(match.group(2)) + (10 if match.group(1)[0] == "a" else 0) 

685 if grade: 

686 return grade 

687 return 100 

688 # canonical, ccds, ensembl, refseq: nothing in this model distinguishes candidates. 

689 return _UNKNOWN_PICK_VALUE