Coverage for src/python/ensembl/vep/sources/file/vcf/variation.py: 93%
217 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"""VCF-backed variation feature sources.
16Two of them, differing only in what a record is: ``VCFVariationSource`` reads parsed records, and
17``PicklableVCFVariationSource`` reads the input's own lines, which is what an annotation run needs
18because a record it hands a worker has to pickle.
19"""
21from __future__ import annotations
23import logging
24import re
25from collections.abc import Iterator, Sequence
27from attrs import define, field
29from ensembl.vep.common.constants import EMPTY_ALLELE
30from ensembl.vep.common import Locus, Strand, format_region_string
31from ensembl.vep.models.sequence import Slice
32from ensembl.vep.models.variation.variation import Variation
33from ensembl.vep.models.variation.structural_variation import StructuralVariation, StructuralVariationAllele
34from ensembl.vep.parsers.vcf import VCFParser
35from ensembl.vep.sources.file.file_feature_source import FileFeatureSource
36from ensembl.vep.sources.synonym import SequenceRegionResolver
37from ensembl.vep.ensembl_vep_core import VCFRecord # noqa: F401,F403 pylint: disable=E0401,E0611
39logger = logging.getLogger(__name__)
41BREAKEND_REGEX = re.compile(
42 r"""\[[^*]+\[ # one or more non-asterisk characters inside opening square brackets
43 | \][^*]+\] # OR one or more non-asterisk characters inside closing square brackets
44 | \.[A-Z]+ # OR a dot followed by base characters
45 | [A-Z]+\. # OR base characters followed by a dot""",
46 re.X,
47)
48SYMBOLIC_ALLELES = ("DEL", "INS", "DUP", "INV", "CNV")
49SVTYPES = ("BND", *SYMBOLIC_ALLELES)
51_MINIMAL_HEADER = "##fileformat=VCFv4.3\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n"
52"""Header lines are parsed against when the input's own header cannot be read."""
54_FIXED_COLUMN_COUNT = 8
55"""How many columns every VCF record has before its optional FORMAT and sample columns."""
57_RAW_LINE_READ_SIZE = 5000
58"""How many record lines one read from the parser hands back.
60An I/O step rather than a batch: how many records are annotated together is decided by whoever
61drives the source, from the execution configuration."""
64@define(kw_only=True, auto_attribs=True)
65class VCFVariationSource(FileFeatureSource[VCFParser, VCFRecord, Variation]):
66 """Variation source backed by a VCF file.
68 Attributes:
69 adaptor: The parser adaptor used to stream VCF records.
70 """
72 adaptor: VCFParser = field(init=False, factory=VCFParser)
73 sequence_region_resolver: SequenceRegionResolver | None = field(default=None)
75 def record_count(self, *, scan: bool = False) -> int | None:
76 """Return how many records the input holds, or None when nothing declares it.
78 Args:
79 scan (bool): Whether to count by reading the whole input when it has no index.
80 Default is False.
82 Returns:
83 int | None: The record count, or None when the input has no index and ``scan`` is
84 False.
85 """
86 return VCFParser.record_count(self.file_path, scan=scan)
88 def records_to_features(self, records: list[VCFRecord]) -> list[Variation]:
89 """Convert VCFRecords into Variation or StructuralVariation objects.
91 Args:
92 records (list[VCFRecord]): VCF records to convert into variation features.
94 Returns:
95 list[Variation]: Variation and StructuralVariation objects created from the VCF records.
96 """
98 features: list[Variation] = []
99 for record in records:
100 if self._is_structural_variation_record(record):
101 features.extend(self._records_to_structural_variation([record]))
102 else:
103 features.extend(self._records_to_variation([record]))
105 return features
107 def _records_to_variation(self, records: list[VCFRecord]) -> list[Variation]:
108 """Convert VCFRecords into Variation objects.
110 Args:
111 records (list[VCFRecord]): VCF records to convert into Variation objects.
113 Returns:
114 list[Variation]: Variation objects created from the VCF records.
115 """
117 variations: list[Variation] = []
118 for record in records:
119 uploaded_allele_string = "/".join([record.reference, *record.alt])
120 uploaded_end = record.pos + len(record.reference) - 1
121 ref, alts, start, end, _ = self._remove_anchor_bases(
122 record.reference,
123 record.alt,
124 start=record.pos,
125 end=uploaded_end,
126 )
127 assert isinstance(alts, list)
128 allele_string = "/".join([ref, *alts])
129 variations.append(
130 Variation(
131 stable_id=self._stable_id_from_vcf_record(record),
132 start=start,
133 end=end,
134 strand=Strand.FORWARD,
135 slice=self.slice_cache.get_slice(
136 self._sequence_region_name(record.chrom),
137 self.sequence_source,
138 ),
139 allele_string=allele_string,
140 uploaded_locus=Locus(
141 seq_region_name=record.chrom,
142 start=record.pos,
143 end=uploaded_end,
144 allele_string=uploaded_allele_string,
145 ),
146 )
147 )
148 return variations
150 def _records_to_structural_variation(self, records: list[VCFRecord]) -> list[StructuralVariation]:
151 """Convert VCFRecords into StructuralVariation objects.
153 Args:
154 records (list[VCFRecord]): VCF records to convert into StructuralVariation objects.
156 Returns:
157 list[StructuralVariation]: StructuralVariation objects created from the VCF records.
158 """
160 structural_variations: list[StructuralVariation] = []
161 for record in records:
162 seq_region_slice = self.slice_cache.get_slice(
163 self._sequence_region_name(record.chrom),
164 self.sequence_source,
165 )
167 variation_alleles = []
168 for i in range(len(record.alt)):
169 variation_alleles.append(
170 self._create_sv_allele_from_record(
171 record, allele_index=i, seq_region_slice=seq_region_slice
172 )
173 )
174 start = record.pos
175 end = max(var.end for var in variation_alleles)
177 structural_variation = StructuralVariation(
178 stable_id=self._stable_id_from_vcf_record(record),
179 start=start,
180 end=end,
181 strand=Strand.FORWARD,
182 slice=seq_region_slice,
183 allele_string="/".join([record.reference, *record.alt]),
184 uploaded_locus=Locus(
185 seq_region_name=record.chrom,
186 start=record.pos,
187 end=end,
188 allele_string="/".join([record.reference, *record.alt]),
189 ),
190 sv_type=self._svtype_from_vcf_record(record),
191 copy_number=self._int_info_value(record, "CN"),
192 )
194 structural_variation.variation_alleles = variation_alleles
196 structural_variations.append(structural_variation)
198 return structural_variations
200 def _sequence_region_name(self, uploaded_name: str) -> str:
201 """Return the source name used to construct a variation slice."""
203 if self.sequence_region_resolver is None:
204 return uploaded_name
205 return self.sequence_region_resolver.resolve(uploaded_name)
207 def _create_sv_allele_from_record(
208 self, record: VCFRecord, *, allele_index: int, seq_region_slice: Slice | None
209 ) -> StructuralVariationAllele:
210 """Create a StructuralVariationAllele object from a VCFRecord.
212 Args:
213 record (VCFRecord): VCF record to convert into StructuralVariation objects.
214 allele_index (int): index of the alt allele to create object for.
215 slice (Slice | None): Slice object to add to StructuralVariationAllele.
217 Returns:
218 StructuralVariationAllele: StructuralVariationAllele object created from the VCF record.
219 """
220 end, svlen = self._end_and_svlen_for_sva_from_vcf_record(record, allele_index)
221 ref, alt, start, end, _ = self._remove_anchor_bases_symbolic_allele(
222 record.reference, record.alt[allele_index], start=record.pos, end=end
223 )
225 return StructuralVariationAllele(
226 start=start,
227 end=end,
228 svlen=svlen,
229 strand=Strand.FORWARD,
230 slice=seq_region_slice,
231 reference_allele=ref,
232 alternate_allele=alt,
233 )
235 def _is_structural_variation_record(self, record: VCFRecord) -> bool:
236 """Return whether the VCF record should be represented as a StructuralVariation.
238 Args:
239 record (VCFRecord): VCF record to inspect for structural-variation hints.
241 Returns:
242 bool: True if the record should be converted to a StructuralVariation, otherwise False.
243 """
245 return not self._is_bases_only(record) and (
246 self._has_svtype(record) or self._is_symbolic(record) or self._is_breakend(record)
247 )
249 @staticmethod
250 def _is_bases_only(record: VCFRecord) -> bool:
251 """Is the VCF record a SNV or short INDEL
253 Args:
254 record (VCFRecord): VCF record to inspect for structural-variation hints.
256 Returns:
257 bool: True if the record only contains nucleotide bases in REF and ALT, otherwise False.
258 """
260 return all(re.fullmatch(r"^[ACGT]+$", allele) for allele in [record.reference, *record.alt])
262 @staticmethod
263 def _has_svtype(record: VCFRecord) -> bool:
264 """Does the record have the SVTYPE info key
266 Args:
267 record (VCFRecord): VCF record to inspect for structural-variation hints.
269 Returns:
270 bool: True if the record has a valid value for SVTYPE, otherwise False.
271 """
273 svtype = VCFVariationSource._svtype_from_vcf_record(record)
274 return svtype in SVTYPES
276 @staticmethod
277 def _svtype_from_vcf_record(record: VCFRecord) -> str | None:
278 """Return the normalized structural-variant type from a VCF record."""
280 svtype = record.info.get("SVTYPE")
281 return svtype.upper() if svtype else None
283 @staticmethod
284 def _is_symbolic(record: VCFRecord) -> bool:
285 """Do any of the ALT alleles match a symbolic allele
287 Args:
288 record (VCFRecord): VCF record to inspect for structural-variation hints.
290 Returns:
291 bool: True if ANY of ALT alleles match a symbolic allele, otherwise False.
292 """
294 # Remove opening angle bracket for comparison
295 alts = [allele.replace("<", "") for allele in record.alt]
296 return any(allele[0:3] in SYMBOLIC_ALLELES for allele in alts)
298 @staticmethod
299 def _is_breakend(record: VCFRecord) -> bool:
300 """Do any of the ALT alleles match a breakend allele
302 Args:
303 record (VCFRecord): VCF record to inspect for structural-variation hints.
305 Returns:
306 bool: True if any of ALT alleles match breakend notation, otherwise False.
307 """
309 return any(re.search(BREAKEND_REGEX, allele) for allele in record.alt)
311 @staticmethod
312 def _is_symbolic_insertion(alt_allele_string: str) -> bool:
313 """Is the symbolic allele an insertion
315 Args:
316 alt_allele_string (str): Alternate allele string
318 Returns:
319 bool: True if the alt string matches an insertion allele.
320 """
322 return alt_allele_string in ("INS", "<INS>")
324 @staticmethod
325 def _stable_id_from_vcf_record(record: VCFRecord) -> str | None:
326 """Return a stable identifier from the VCF ID column, when present.
328 Args:
329 record (VCFRecord): VCF record containing ID values.
331 Returns:
332 str | None: Semicolon-delimited stable identifier, or None when the record has no IDs.
333 """
335 return ";".join(record.id) or None
337 def _end_and_svlen_for_sva_from_vcf_record(
338 self, record: VCFRecord, allele_index: int
339 ) -> tuple[int | None, int | None]:
340 """Return the VCF record end coordinate and length for an allele.
342 Args:
343 record (VCFRecord): VCF record.
344 allele_index: index for the allele.
346 Returns:
347 tuple: (End coordinate, SV length).
348 """
350 if allele_index >= len(record.alt):
351 logger.warning(f"Allele index, {allele_index}, is too large, {';'.join(record.id)}")
352 return (None, None)
354 lengths = record.info.get("SVLEN")
355 if lengths is not None:
356 svlen = lengths.split(",")[allele_index]
357 svlen = None if svlen == "." else abs(int(svlen))
358 if svlen is None:
359 end = record.pos + len(record.reference) - 1
360 else:
361 end = record.pos + svlen
362 else:
363 end = self._int_info_value(record, "END")
364 if end is None:
365 svlen = None
366 else:
367 svlen = abs(end - record.pos)
369 # For insertions, end is not POS + SVLEN
370 if self._is_symbolic_insertion(record.alt[allele_index]):
371 end = record.pos + len(record.reference) - 1
373 if end is None or svlen is None:
374 logger.warning(f"Could not determine END/SVLEN for {record.id}")
376 return end, svlen
378 @staticmethod
379 def _int_info_value(record: VCFRecord, key: str) -> int | None:
380 """Return an INFO value parsed as an integer.
382 Args:
383 record (VCFRecord): VCF record containing INFO values.
384 key (str): INFO field key to parse.
386 Returns:
387 int | None: Parsed integer value, or None when the key is absent or not an integer.
388 """
390 value = record.info.get(key)
391 if value is None:
392 return None
394 try:
395 return int(value)
396 except (TypeError, ValueError):
397 return None
399 @staticmethod
400 def _remove_anchor_bases(
401 ref: str,
402 alt: str | list[str],
403 *,
404 start: int = 0,
405 end: int | None = None,
406 strand: Strand = Strand.FORWARD,
407 ) -> tuple[str, str | list[str], int, int, bool]:
408 """Remove common leading anchor bases from non-symbolic alleles.
410 For multi-allelic variants, only bases shared by the reference and every alternate allele are
411 removed so that all alleles retain a common locus.
413 Args:
414 ref: Reference allele sequence.
415 alt: One alternate allele or a list of alternate alleles.
416 start: Start coordinate.
417 end: End coordinate. Defaults to ``start + len(ref) - 1``.
418 strand: Strand on which the alleles are represented.
420 Returns:
421 Tuple of (new_ref, new_alt, new_start, new_end, changed). Empty alleles are represented by
422 ``-`` and the shape of ``new_alt`` matches the input.
423 """
425 end = end if end is not None else start + len(ref) - 1
427 # Alternate alleles can be a single string or a list of strings. Normalize to a list for processing.
428 if isinstance(alt, str):
429 alt_is_string = True
430 alt_alleles = [alt]
431 else:
432 alt_is_string = False
433 alt_alleles = alt.copy()
434 if not alt_alleles: 434 ↛ 435line 434 didn't jump to line 435 because the condition on line 434 was never true
435 return (ref, alt, start, end, False)
437 if strand == Strand.UNKNOWN:
438 logger.warning(
439 "Strand is unknown, cannot remove anchor bases with confidence. "
440 "Returning unmodified alleles."
441 )
442 return (ref, alt, start, end, False)
444 alleles = [ref, *alt_alleles]
445 changed = False
447 while all(alleles) and len({allele[0] for allele in alleles}) == 1:
448 alleles = [allele[1:] for allele in alleles]
449 if strand == Strand.REVERSE: 449 ↛ 450line 449 didn't jump to line 450 because the condition on line 449 was never true
450 end -= 1
451 else:
452 start += 1
453 changed = True
455 new_ref = alleles[0] or EMPTY_ALLELE
456 new_alts = [allele or EMPTY_ALLELE for allele in alleles[1:]]
457 new_alt: str | list[str] = new_alts[0] if alt_is_string else new_alts
458 return (new_ref, new_alt, start, end, changed)
460 @staticmethod
461 def _remove_anchor_bases_symbolic_allele(
462 ref: str,
463 alt: str,
464 *,
465 start: int = 0,
466 end: int | None,
467 strand: Strand = Strand.FORWARD,
468 ) -> tuple[str, str, int, int, bool]:
469 """Remove the reference anchor bases from a symbolic allele.
471 Converts symbolic allele in the form A/<DEL> to -/<DEL>, adjusting coordinates accordingly.
473 Args:
474 ref: Reference allele sequence.
475 alt: Alternate allele sequence.
476 start: Start coordinate (default 0).
477 end: End coordinate (default: start + len(ref) - 1).
478 strand: 1 for forward, -1 for reverse strand.
480 Returns:
481 Tuple of (new_ref, new_alt, new_start, new_end, changed).
482 """
484 end = end or (start + (len(ref) - 1))
486 changed = False
488 if strand == Strand.UNKNOWN:
489 logger.warning(
490 "Strand is unknown, cannot trim alleles with confidence. Returning untrimmed alleles."
491 )
492 return (ref, alt, start, end, changed)
494 if ref == EMPTY_ALLELE:
495 logger.warning("Allele is already trimmed. Returning untrimmed alleles.")
496 return (ref, alt, start, end, changed)
498 if strand == Strand.REVERSE:
499 end -= len(ref)
500 else:
501 start += len(ref)
502 ref = EMPTY_ALLELE
503 changed = True
505 return (ref, alt, start, end, changed)
508@define(kw_only=True, auto_attribs=True)
509class PicklableVCFVariationSource(VCFVariationSource):
510 """VCF variation source whose records are the input's own lines.
512 An annotation run reads in one process and builds models in another: the process driving the
513 run reads records and the worker annotating them turns records into variations. A record has
514 to pickle to make that crossing, which the Rust parser's ``VCFRecord`` does not, and output
515 has to echo the input's own text back, which a record built from a line can no longer give.
516 The line is both, so this source's record is a line -- narrowing the record type its parent
517 reads, and leaving everything about building models from them the same.
519 Nothing here batches. ``iter_all_records`` yields one record at a time and whoever drives the
520 source groups them (``workflow.executor.PayloadIterator``), which is what lets a format say
521 what a record is without also deciding how many of them cross a process boundary at once.
522 """
524 _header_text: str | None = field(default=None, init=False, repr=False)
526 def header_lines(self) -> list[str]:
527 """Return the input's leading header lines, without line endings."""
528 with VCFParser(file_path=self.file_path, mode="sequential") as parser:
529 return list(parser.metadata["header"])
531 def get_all_records(self) -> list[str]:
532 """Return every record line in the input, in input order."""
533 return list(self.iter_all_records())
535 def iter_all_records(self) -> Iterator[str]:
536 """Yield each record's line, as the input spells it, without its line ending.
538 Yields:
539 Iterator[str]: Each record's line, in input order.
541 Raises:
542 ValueError: If a line holds fewer than the eight fixed VCF columns.
543 """
544 with VCFParser(file_path=self.file_path, mode="sequential") as parser:
545 while lines := parser.raw_lines(_RAW_LINE_READ_SIZE):
546 for line in lines:
547 yield self._validated(line)
549 def get_records_by_region(
550 self,
551 region: str | None = None,
552 *,
553 seq_region_name: str | None = None,
554 start: int | None = None,
555 end: int | None = None,
556 **kwargs: object,
557 ) -> list[str]:
558 """Return the record lines an indexed region query reads.
560 Args:
561 region (str | None): The region (e.g., "chr1:1000-2000") to read.
562 seq_region_name (str | None): The name of the sequence region (e.g., "chr1").
563 start (int | None): The start position of the region.
564 end (int | None): The end position of the region.
565 **kwargs (object): Unused here; a format whose query takes more accepts it.
567 Returns:
568 list[str]: The record lines the query read, empty when the region names none.
569 """
570 del kwargs
571 return list(self._iter_region_lines(region, seq_region_name, start, end, read_size=None))
573 def iter_records_by_region(
574 self,
575 region: str | None = None,
576 *,
577 seq_region_name: str | None = None,
578 start: int | None = None,
579 end: int | None = None,
580 **kwargs: object,
581 ) -> Iterator[str]:
582 """Yield the record lines an indexed region query reads.
584 Args:
585 region (str | None): The region (e.g., "chr1:1000-2000") to read.
586 seq_region_name (str | None): The name of the sequence region (e.g., "chr1").
587 start (int | None): The start position of the region.
588 end (int | None): The end position of the region.
589 **kwargs (object): Unused here; a format whose query takes more accepts it.
591 Returns:
592 Iterator[str]: The record lines the query reads, in file order.
593 """
594 del kwargs
595 return self._iter_region_lines(region, seq_region_name, start, end, read_size=_RAW_LINE_READ_SIZE)
597 def records_to_features(self, records: Sequence[str]) -> list[Variation]:
598 """Return the variations for a set of record lines, in input order.
600 A record is a line alone, so the file's own header is read back here: what a line means
601 can depend on an INFO or contig declaration that only the header holds.
603 Args:
604 records (Sequence[str]): The record lines to parse and build models from.
606 Returns:
607 list[Variation]: The variations the lines describe.
608 """
609 return super().records_to_features(VCFParser.parse_text(self._parsed_header() + "\n".join(records)))
611 @staticmethod
612 def region_of(record: str) -> str:
613 """Return the sequence region a record names.
615 Args:
616 record (str): The record line to read.
618 Returns:
619 str: Its sequence-region name, taken from the line's first field rather than from all
620 of them: this is read once per record in the process driving a run, and the whole
621 line is split again only for the records output echoes.
622 """
623 return record.partition("\t")[0]
625 @staticmethod
626 def record_columns(record: str) -> tuple[str, ...]:
627 """Return a record's own columns, which output echoes back as the input gave them.
629 Args:
630 record (str): The record line to split.
632 Returns:
633 tuple[str, ...]: Its columns, in input order.
634 """
635 return tuple(record.split("\t"))
637 def _iter_region_lines(
638 self,
639 region: str | None,
640 seq_region_name: str | None,
641 start: int | None,
642 end: int | None,
643 *,
644 read_size: int | None,
645 ) -> Iterator[str]:
646 """Yield the record lines of one region query, reading ``read_size`` lines at a time."""
647 try:
648 query_region = format_region_string(region, seq_region_name=seq_region_name, start=start, end=end)
649 except ValueError:
650 logger.debug("Cannot parse region: %s %s:%s-%s", region, seq_region_name, start, end)
651 return
652 with VCFParser(file_path=self.file_path, mode="query") as parser:
653 if not parser.seek(query_region):
654 return
655 while lines := parser.raw_lines(read_size):
656 for line in lines:
657 yield self._validated(line)
659 def _parsed_header(self) -> str:
660 """Return the header text records are parsed against, read from the file once per source."""
661 if self._header_text is None:
662 try:
663 headers = self.header_lines()
664 # A header the parser rejects arrives as a ValueError, a missing file as an OSError.
665 except (OSError, ValueError) as error:
666 logger.warning(
667 f"Could not read the VCF header of {self.file_path} ({error});"
668 "parsing records against a minimal header"
669 )
670 headers = []
671 self._header_text = "\n".join(headers) + "\n" if headers else _MINIMAL_HEADER
672 return self._header_text
674 @staticmethod
675 def _validated(line: str) -> str:
676 """Return a record line, refusing one that cannot hold a record.
678 Args:
679 line (str): The record line to check.
681 Returns:
682 str: The line itself.
684 Raises:
685 ValueError: If the line holds fewer than the eight fixed VCF columns. Counted rather
686 than split: nothing here needs the fields, and the parser splits the line again
687 anyway.
688 """
689 if line.count("\t") < _FIXED_COLUMN_COUNT - 1:
690 raise ValueError("a VCF record must contain at least eight columns")
691 return line