Coverage for src/python/ensembl/vep/explain/selection.py: 96%
218 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"""Overlap selection for consequence explanations.
16Explaining one derivation needs one ``(variant, transcript)`` pair out of a real input, which is a
17different job from annotating a whole file: there is no buffering, no output, and reading the whole
18input to pair every variant would be waste when the caller named one. What it must not be is a
19second opinion about which pairs exist -- so the pairing here is built by the transcript track's
20own ``build_transcript_overlap_finder`` over the same sources the run path builds, and only the
21*search* is explain's own.
23The two kinds of source answer the same question differently: a file is searched for the named
24variant alone, pairing no more of it than that takes, while a generated corpus is walked, there
25being nothing to query. ``OverlapSelection`` holds that choice for one run, reading each source
26lazily and at most once, so selecting by name costs one pass and selecting nothing costs none.
27"""
29from __future__ import annotations
31import logging
32from collections.abc import Iterator, Sequence
33from contextlib import closing
34from pathlib import Path
35from typing import Generator
37from attrs import define, field
39from ensembl.vep.buffer import FixedSizeInputBuffer
40from ensembl.vep.common.constants import EMPTY_ALLELE
41from ensembl.vep.config import Config
42from ensembl.vep.corpus.base import Corpus
43from ensembl.vep.corpus.registry import build_corpus
44from ensembl.vep.corpus.spec import CorpusSpec
45from ensembl.vep.models.genic.transcript import Transcript
46from ensembl.vep.models.overlap import TranscriptVariationAllele
47from ensembl.vep.models.variation.variation import Variation
48from ensembl.vep.models.variation.variation_allele import VariationAllele
49from ensembl.vep.sources.build import (
50 InputSource,
51 TranscriptSource,
52 build_chromosome_synonyms,
53 build_input_source,
54 build_sequence_source,
55 build_transcript_source,
56)
57from ensembl.vep.workflow.tracks import build_transcript_overlap_finder, transcript_candidate_window
59__all__ = ["FeatureSelector", "NamedOverlap", "OverlapSelection", "VariantSelector"]
61logger = logging.getLogger(__name__)
63NamedOverlap = tuple[str, TranscriptVariationAllele]
64"""One overlap and the name of the variant it came from."""
67def _normalised_allele(value: str | None) -> str:
68 """Return an allele in the single spelling a selector comparison can rely on.
70 An empty allele is spelled ``""`` by the generated corpus and ``"-"`` by the VCF reader, which
71 follows VEP. Selecting an overlap must work the same way whichever source produced it, so both
72 collapse to ``""`` here. Without this, a selector matched SNVs from a file but never indels.
74 Args:
75 value (str | None): The allele as the model stores it.
77 Returns:
78 str: The allele upper-cased, with either spelling of "empty" as an empty string.
79 """
80 if value is None or value == EMPTY_ALLELE:
81 return ""
82 return value.upper()
85@define(frozen=True, kw_only=True, auto_attribs=True)
86class VariantSelector:
87 """Variant selector written as ``CHR:POS:REF>ALT`` or ``CHR:POS:ID``.
89 The two forms locate a variant differently. ``REF>ALT`` names one allele by its minimised
90 coordinates, as the model stores them. ``ID`` names a record by the identifier and position the
91 input gives it -- a VCF's ID and POS columns -- and ``allele_num`` picks one of its alternate
92 alleles.
94 Attributes:
95 seq_region_name (str): Sequence region name.
96 position (int): The allele's start for ``REF>ALT``, the input's own position for ``ID``.
97 reference_allele (str | None): Upper-cased reference allele, ``""`` when empty; None for ``ID``.
98 alternate_allele (str | None): Upper-cased alternate allele, ``""`` when empty; None for ``ID``.
99 identifier (str | None): The variant's identifier in the input; None for ``REF>ALT``.
100 allele_num (int): Which alternate allele an ``ID`` selects, counting from 1.
101 """
103 seq_region_name: str
104 position: int
105 reference_allele: str | None = None
106 alternate_allele: str | None = None
107 identifier: str | None = None
108 allele_num: int = 1
110 @classmethod
111 def parse(cls, selector: str, *, allele_num: int | None = None) -> VariantSelector:
112 """Parse a selector, with ``-`` for an empty allele.
114 Args:
115 selector (str): ``CHR:POS:REF>ALT``, e.g. ``chr1:1052:->ACG`` for an insertion before 1052,
116 or ``CHR:POS:ID``, e.g. ``22:15528194:rs123``.
117 allele_num (int | None): The alternate allele an ``ID`` selects, counting from 1. None means
118 the first.
120 Returns:
121 VariantSelector: The parsed selector.
123 Raises:
124 ValueError: If the selector does not have either shape, or ``allele_num`` is given for a
125 ``REF>ALT`` selector, which already names its allele, or is below 1.
126 """
127 parts = selector.split(":", 2)
128 if len(parts) != 3 or not parts[2]:
129 raise ValueError(f"expected a variant as CHR:POS:REF>ALT or CHR:POS:ID, got {selector!r}")
130 seq_region_name, position_text, detail = parts
131 try:
132 position = int(position_text)
133 except ValueError as error:
134 raise ValueError(f"expected an integer position in {selector!r}") from error
136 if ">" not in detail:
137 if allele_num is not None and allele_num < 1:
138 raise ValueError(f"allele numbers count alternate alleles from 1, got {allele_num}")
139 return cls(
140 seq_region_name=seq_region_name,
141 position=position,
142 identifier=detail,
143 allele_num=allele_num or 1,
144 )
146 if allele_num is not None:
147 raise ValueError(
148 f"an allele number selects from a CHR:POS:ID variant; {selector!r} names its allele"
149 )
150 reference_allele, alternate_allele = detail.split(">", 1)
151 return cls(
152 seq_region_name=seq_region_name,
153 position=position,
154 reference_allele=_normalised_allele(reference_allele),
155 alternate_allele=_normalised_allele(alternate_allele),
156 )
158 @property
159 def query_span(self) -> tuple[int, int]:
160 """Return the 1-based query span covering this variant's input record.
162 One base before the position as well, because a VCF anchors an indel on the preceding base
163 and the minimised start of an insertion lies after it.
164 """
165 return max(1, self.position - 1), self.position
167 def matches(self, allele: VariationAllele) -> bool:
168 """Return whether an allele is the one this selector names."""
169 seq_region_name = allele.slice.seq_region_name if allele.slice is not None else None
170 if seq_region_name != self.seq_region_name:
171 return False
172 if self.identifier is None:
173 return (
174 allele.start == self.position
175 and _normalised_allele(allele.reference_allele) == self.reference_allele
176 and _normalised_allele(allele.alternate_allele) == self.alternate_allele
177 )
179 variation = allele.variation
180 if variation is None or not variation.stable_id:
181 return False
182 if self.identifier not in variation.stable_id.split(";"):
183 return False
184 uploaded_start = (
185 variation.uploaded_locus.start if variation.uploaded_locus is not None else variation.start
186 )
187 if uploaded_start != self.position:
188 return False
189 alleles = variation.variation_alleles or ()
190 return len(alleles) >= self.allele_num and alleles[self.allele_num - 1] is allele
193@define(frozen=True, kw_only=True, auto_attribs=True)
194class FeatureSelector:
195 """Feature selector using a stable identifier and optional GFF3 type prefix.
197 A GFF3 spells a transcript's id ``transcript:ENST00000775241`` and the reader keeps it, while a
198 caller naturally types ``ENST00000775241``; both name the same feature.
200 Attributes:
201 stable_id (str): The stable id the caller typed, either spelling.
202 """
204 stable_id: str
206 @classmethod
207 def parse(cls, selector: str) -> FeatureSelector:
208 """Parse a feature selector.
210 Args:
211 selector (str): A stable id, e.g. ``ENST00000775241`` or ``transcript:ENST00000775241``.
213 Returns:
214 FeatureSelector: The parsed selector.
216 Raises:
217 ValueError: If the selector is empty.
218 """
219 if not selector:
220 raise ValueError("expected a feature stable id, got an empty selector")
221 return cls(stable_id=selector)
223 def matches(self, feature: Transcript) -> bool:
224 """Return whether a feature is the one this selector names.
226 A prefix match is not a match: the id after the prefix has to be the same one.
227 """
228 return self.stable_id in (feature.stable_id, feature.stable_id.split(":", 1)[-1])
231@define(kw_only=True, auto_attribs=True)
232class OverlapSelection:
233 """Selectable overlaps and the sources used to find them.
235 Attributes:
236 config (Config): The run's configuration; its ``source``, ``corpus`` and ``explain``
237 sections say where the overlaps come from and which one is wanted.
238 sources (tuple[InputSource, TranscriptSource] | None): The two readers, built from
239 the configuration on first use. Assignable so a caller can supply readers of its own
240 -- a test over in-memory sequence, say -- instead of real files.
241 """
243 config: Config
244 sources: tuple[InputSource, TranscriptSource] | None = field(init=False, default=None)
245 _built_corpus: Corpus | None = field(init=False, default=None)
247 def close(self) -> None:
248 """Release the generated corpus, if one was built."""
249 if self._built_corpus is not None:
250 self._built_corpus.close()
251 self._built_corpus = None
253 def select(self) -> NamedOverlap:
254 """Return the single overlap the selectors identify.
256 A name or a variant identifies the variant, not the overlap, so one that pairs with several
257 features needs ``--transcript`` as well. Saying which stable ids matched is the whole value
258 of the error, so the message names them.
260 Returns:
261 NamedOverlap: The selected overlap and the name it came under.
263 Raises:
264 LookupError: If nothing matches, if several do and no feature was named, or if the
265 index is past the end.
266 ValueError: If the variant selector is malformed, or an allele number was given
267 without a ``CHR:POS:ID`` variant.
268 """
269 explain = self.config.explain
270 if explain.index is not None:
271 for position, named_overlap in enumerate(self.all_overlaps()):
272 if position == explain.index:
273 return named_overlap
274 raise LookupError(f"index {explain.index} is past the end of {self.description()}")
276 if explain.allele_num is not None and explain.variant is None:
277 raise ValueError("an allele number selects from a CHR:POS:ID variant; give the variant too")
278 selector = (
279 VariantSelector.parse(explain.variant, allele_num=explain.allele_num)
280 if explain.variant is not None
281 else None
282 )
283 selector_text = explain.name if explain.name is not None else explain.variant
284 feature = FeatureSelector.parse(explain.transcript) if explain.transcript is not None else None
286 matches: list[NamedOverlap] = []
287 for candidate_name, overlap in self.candidate_overlaps(explain.name, selector):
288 if explain.name is not None and candidate_name != explain.name:
289 continue
290 if selector is not None and not selector.matches(overlap.overlapping_feature):
291 continue
292 if feature is not None and not feature.matches(overlap.feature): 292 ↛ 293line 292 didn't jump to line 293 because the condition on line 292 was never true
293 continue
294 matches.append((candidate_name, overlap))
295 if feature is not None:
296 # A named feature makes the pair unique, so nothing later can make this ambiguous.
297 break
299 if not matches:
300 suffix = f" for feature {explain.transcript!r}" if feature is not None else ""
301 raise LookupError(f"no overlap matching {selector_text!r} in {self.description()}{suffix}")
302 if len(matches) > 1:
303 stable_ids = sorted({overlap.feature.stable_id for _name, overlap in matches})
304 raise LookupError(
305 f"{len(matches)} overlaps match {selector_text!r} (features: {', '.join(stable_ids)}); "
306 "disambiguate by naming one"
307 )
308 return matches[0]
310 def candidate_overlaps(
311 self, name: str | None = None, selector: VariantSelector | None = None
312 ) -> Iterator[NamedOverlap]:
313 """Yield the overlaps that could match, pairing no more of the input than it takes.
315 A real input is searched for the named variant alone; a generated corpus is walked, there
316 being nothing to query, and is returned unfiltered for the caller to sift.
318 Args:
319 name (str | None): The variant name to look for.
320 selector (VariantSelector | None): The variant's locus and alleles, or its identifier.
322 Yields:
323 NamedOverlap: Every overlap that still has to be filtered by the caller.
324 """
325 if self.config.source.input_file is None:
326 yield from self._corpus().named_overlaps
327 return
328 for allele_name, allele in self._get_candidate_variation_alleles(name=name, selector=selector):
329 for overlap in self._pair(allele, self._get_candidate_features(allele)):
330 yield allele_name, overlap
332 def all_overlaps(self) -> Iterator[NamedOverlap]:
333 """Yield every selectable overlap, in the order ``--index`` counts.
335 Pairing every variant means reading both files whole: an un-indexed GFF3 or GTF cannot
336 serve a region query at all, and a caller asking for the listing has asked for all of
337 them. The transcripts are grouped by sequence region once, rather than queried per
338 variant, which is what keeps this one pass over each file.
339 """
340 if self.config.source.input_file is None:
341 yield from self._corpus().named_overlaps
342 return
344 transcripts_by_region: dict[str, list[Transcript]] = {}
345 for transcript in self._get_candidate_features():
346 region = transcript.slice.seq_region_name if transcript.slice is not None else None
347 if region is not None: 347 ↛ 345line 347 didn't jump to line 345 because the condition on line 347 was always true
348 transcripts_by_region.setdefault(region, []).append(transcript)
350 for name, allele in self._get_candidate_variation_alleles():
351 assert allele.slice is not None
352 nearby = transcripts_by_region.get(allele.slice.seq_region_name, ())
353 for overlap in self._pair(allele, nearby):
354 yield name, overlap
356 def _get_candidate_variation_alleles(
357 self, *, name: str | None = None, selector: VariantSelector | None = None
358 ) -> Iterator[tuple[str, VariationAllele]]:
359 """Yield named alleles from the input: every one, or the ones a name or selector identifies.
361 Filtered, this stops at the first variation with any allele matching, which is what makes
362 selecting by name cost a partial pass rather than a whole file. The input is queried by
363 region where a selector gives a position and the file has an index.
365 Args:
366 name (str | None): The variant name to look for, as ``display_name`` spells it.
367 selector (VariantSelector | None): The variant's locus and alleles, or its identifier.
369 Yields:
370 tuple[str, VariationAllele]: Each allele and the name it is known by.
371 """
372 variation_source, _transcript_source = self._file_sources()
373 wanted = name is not None or selector is not None
375 def variations() -> Generator[Variation, None, None]:
376 """Yield the variations that could match, from a region query where there is an index."""
377 if selector is None:
378 yield from variation_source.iter_all_features()
379 return
380 start, end = selector.query_span
381 try:
382 found = variation_source.get_features_by_region(
383 seq_region_name=selector.seq_region_name, start=start, end=end
384 )
385 except OSError:
386 logger.info("the variant input has no region index; reading it in order to the first match")
387 yield from variation_source.iter_all_features()
388 return
389 yield from found
391 with closing(variations()) as candidates:
392 for variation in candidates:
393 matched = []
394 for allele in variation.variation_alleles or ():
395 if allele.slice is None: 395 ↛ 396line 395 didn't jump to line 396 because the condition on line 395 was never true
396 logger.warning("skipping an allele with no sequence region: %r", allele)
397 continue
398 allele_name = allele.display_name
399 if name is not None and allele_name != name:
400 continue
401 if selector is not None and not selector.matches(allele):
402 continue
403 matched.append((allele_name, allele))
404 yield from matched
405 if matched and wanted:
406 return
408 def _get_candidate_features(self, allele: VariationAllele | None = None) -> Sequence[Transcript]:
409 """Return the transcripts one allele could pair with, or every transcript in the file.
411 One allele's window is a region query where the file has an index, and a stream of just
412 that window where it has not. The window is the transcript track's own, so a transcript
413 fetched here is one a run would have fetched for the same allele.
415 Args:
416 allele (VariationAllele | None): The allele to fetch a window around, or None for all.
418 Returns:
419 Sequence[Transcript]: The candidate transcripts.
420 """
421 _variation_source, transcript_source = self._file_sources()
422 if allele is None:
423 return list(transcript_source.get_all_features())
425 assert allele.slice is not None
426 region = allele.slice.seq_region_name
427 widest = transcript_candidate_window(self.config)
428 start = max(1, min(allele.start, allele.end) - widest)
429 end = max(allele.start, allele.end) + widest
430 try:
431 return transcript_source.get_features_by_region(seq_region_name=region, start=start, end=end)
432 except OSError:
433 logger.info(
434 "the transcript file has no region index; streaming it for %s:%d-%d", region, start, end
435 )
436 return list(
437 transcript_source.iter_features_by_region(seq_region_name=region, start=start, end=end)
438 )
440 def _pair(
441 self, allele: VariationAllele, transcripts: Sequence[Transcript]
442 ) -> Iterator[TranscriptVariationAllele]:
443 """Pair one allele with the transcripts it meets, by the run path's own rule.
445 The candidates are the transcripts already found here, so the track's finder pairs them
446 without any of the caching a run wants around it.
447 """
448 finder = build_transcript_overlap_finder(self.config, lambda _buffer: transcripts)
449 yield from finder.find(FixedSizeInputBuffer(objects=(allele,)))
451 def _file_sources(self) -> tuple[InputSource, TranscriptSource]:
452 """Build the input and transcript sources the options name, once per run.
454 The same builders the run path uses, so a variant explained here is read, named and
455 resolved exactly as a run would read, name and resolve it.
457 Returns:
458 tuple[InputSource, TranscriptSource]: The input source and transcript source.
460 Raises:
461 ValueError: If the transcript files are ambiguous or absent, or no input file was given.
462 """
463 if self.sources is not None:
464 return self.sources
466 config = self.config.source
467 synonyms = build_chromosome_synonyms(config)
468 if config.fasta is None:
469 # A run refuses this; explaining is allowed to go on without it, and says what is
470 # lost. The sequence facts then have no bases and a slice cannot resolve its region's
471 # length.
472 logger.warning(
473 "no --fasta given: slices cannot resolve a sequence-region length and sequence facts "
474 "have no bases to read"
475 )
476 sequence_source = None
477 else:
478 sequence_source = build_sequence_source(config)
480 self.sources = (
481 build_input_source(config, sequence_source=sequence_source, synonyms=synonyms),
482 build_transcript_source(config, sequence_source=sequence_source, synonyms=synonyms),
483 )
484 return self.sources
486 def _corpus(self) -> Corpus:
487 """Return the generated corpus the options describe."""
488 if self._built_corpus is None:
489 self._built_corpus = build_corpus(CorpusSpec.from_options(self.config.corpus))
490 return self._built_corpus
492 def description(self) -> str:
493 """Describe where the overlaps come from, for an error or a log line."""
494 source = self.config.source
495 if source.input_file is None: 495 ↛ 497line 495 didn't jump to line 497 because the condition on line 495 was always true
496 return self._corpus().description
497 features = source.gff if source.gff is not None else source.gtf
498 feature_name = "no transcripts" if features is None else Path(features).name
499 distance = ",".join(str(value) for value in source.distance)
500 return f"{Path(source.input_file).name} against {feature_name} (distance {distance})"
502 def listing(self) -> str:
503 """Return every selectable overlap, one per line, as index, name and feature."""
504 lines = []
505 for index, (name, overlap) in enumerate(self.all_overlaps()):
506 lines.append(f"[{index:>5}] {name:<42} {overlap.feature.stable_id}")
507 return "\n".join(lines)