Coverage for src/python/ensembl/vep/output/parser/vcf.py: 95%
91 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"""Annotated VCF consequence parsing.
16VEP writes them as ``CSQ`` and SnpEff as ``ANN``: one INFO field whose layout the header's
17``Description`` declares, one entry per (allele, feature) separated by commas, fields by pipes,
18several terms by ``&``. Both are read the same way; only the field names differ.
20Two mechanics that must stay right, both confirmed on this codebase:
22* ``seed_attrs`` takes the *public* name and prepends the underscore itself:
23 ``seed_attrs(overlap_consequences=...)``, never ``_overlap_consequences``.
24* ``transcript_variation_alleles`` carries ``on_setattr=invalidates("_overlap_consequences")``, so
25 assigning it after seeding silently wipes the seed. This reader never assigns it, which is also
26 why it needs no ``--gff``/``--fasta``: the terms live on the allele, and
27 ``Variation.most_severe_consequence`` and ``.class_so_term`` answer with zero transcripts.
28"""
30from __future__ import annotations
32import re
33from collections.abc import Iterator, Sequence
34from pathlib import Path
36from attrs import define, field
38from ensembl.vep.annotators.consequence.rules.rulesets import FactRuleSet, build_fact_ruleset
39from ensembl.vep.common import CoordSystemLevel, Locus, Strand
40from ensembl.vep.common.constants import EMPTY_ALLELE
41from ensembl.vep.models.overlap import OverlapConsequence
42from ensembl.vep.models.sequence import CoordSystem, Slice
43from ensembl.vep.models.variation import Variation
44from ensembl.vep.output.parser.base import OutputParser
45from ensembl.vep.parsers.vcf import VCFParser, VCFRecord
47__all__ = ["ANNOTATION_FIELDS", "UNKNOWN_RANK", "VCFOutputParser", "csq_alleles", "parser_for"]
49ANNOTATION_FIELDS = {"CSQ": ("Allele", "Consequence"), "ANN": ("Allele", "Annotation")}
50"""INFO key -> the names of its allele and consequence fields, as each tool spells them."""
52UNKNOWN_RANK = 999
53"""Rank given to a term the catalogue does not model. Rank 1 is the most severe and the model's
54default is 0, so an unranked term must sit *below* every real one rather than above."""
56_FORMAT_PATTERN = re.compile(r"Format:\s*(.+)$")
59def annotation_layouts(metadata: dict) -> dict[str, list[str]]:
60 """Return each annotation INFO key present in a header with the field names it declares.
62 Args:
63 metadata (dict): ``VCFParser.metadata``.
65 Returns:
66 dict[str, list[str]]: INFO key -> field names, for every key in ``ANNOTATION_FIELDS`` the
67 header declares.
68 """
69 layouts: dict[str, list[str]] = {}
70 for key in ANNOTATION_FIELDS:
71 declaration = metadata.get("info", {}).get(key)
72 if declaration is None:
73 continue
74 description = declaration.get("description", "")
75 match = _FORMAT_PATTERN.search(description)
76 # VEP says "Format: A|B|C"; SnpEff quotes the list: 'A | B | C'.
77 field_text = match.group(1) if match else description.split("'")[1] if "'" in description else ""
78 layouts[key] = [name.strip() for name in field_text.strip("'\" ").split("|")]
79 return layouts
82def csq_alleles(reference: str, alternates: Sequence[str]) -> list[str]:
83 """Return how VEP spells each alternate allele in the CSQ ``Allele`` field.
85 An SNV is its base. When every allele shares the reference's first base -- an indel with its
86 VCF padding -- that base is dropped and an allele left empty becomes ``-``.
87 """
88 shares_padding = bool(reference) and all(
89 alternate and alternate[0] == reference[0] for alternate in alternates
90 )
91 if shares_padding and (len(reference) > 1 or any(len(alternate) > 1 for alternate in alternates)):
92 return [alternate[1:] or EMPTY_ALLELE for alternate in alternates]
93 return list(alternates)
96@define(kw_only=True, auto_attribs=True)
97class VCFOutputParser(OutputParser):
98 """Parser for annotated VCF files.
100 Attributes:
101 ruleset (FactRuleSet): Where a known term's rank, accession and impact come from. A term
102 the catalogue does not model is kept, with ``UNKNOWN_RANK``.
103 """
105 ruleset: FactRuleSet = field(factory=build_fact_ruleset)
107 def parse(self, path: str | Path) -> Iterator[Variation]:
108 """Yield one variation per record.
110 Args:
111 path (str | Path): The annotated VCF.
113 Yields:
114 Variation: Each record, its alleles seeded with the terms the file assigned them.
115 """
116 parser = VCFParser()
117 with parser.open(path):
118 layouts = annotation_layouts(parser.metadata)
119 while (record := parser.next()) is not None:
120 yield self._variation(record, layouts)
122 def _variation(self, record: VCFRecord, layouts: dict[str, list[str]]) -> Variation:
123 """Build one variation from a record and seed its alleles' consequences."""
124 reference = record.reference
125 alternates = list(record.alt)
126 end = record.pos + len(reference) - 1
127 chromosome = Slice(
128 coord_system=CoordSystem(name="chromosome", level=CoordSystemLevel.CHROMOSOME),
129 seq_region_name=record.chrom,
130 start=1,
131 end=end,
132 strand=Strand.FORWARD,
133 )
134 variation = Variation(
135 start=record.pos,
136 end=end,
137 strand=Strand.FORWARD,
138 slice=chromosome,
139 stable_id=record.id[0] if record.id else None,
140 allele_string="/".join([reference, *alternates]),
141 # The record read back is the uploaded one: nothing resolved its name on the way here,
142 # so the file's own spelling is both the slice's and the uploaded locus's.
143 uploaded_locus=Locus(
144 seq_region_name=record.chrom,
145 start=record.pos,
146 end=end,
147 allele_string="/".join([reference, *alternates]),
148 ),
149 )
151 terms_by_index = self._terms_by_allele_index(record, layouts, reference, alternates)
152 for index, allele in enumerate(variation.variation_alleles):
153 consequences = [self._consequence(term) for term in terms_by_index.get(index, [])]
154 allele.seed_attrs(overlap_consequences=consequences)
155 return variation
157 def _terms_by_allele_index(
158 self, record: VCFRecord, layouts: dict[str, list[str]], reference: str, alternates: list[str]
159 ) -> dict[int, list[str]]:
160 """Return the terms each alternate allele carries, by its position in ``ALT``."""
161 terms: dict[int, list[str]] = {}
162 for key, names in layouts.items():
163 raw = record.info.get(key)
164 if not raw:
165 continue
166 allele_field, term_field = ANNOTATION_FIELDS[key]
167 if allele_field not in names or term_field not in names: 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true
168 continue
169 allele_index, term_index = names.index(allele_field), names.index(term_field)
170 spellings = csq_alleles(reference, alternates) if key == "CSQ" else alternates
171 for entry in str(raw).split(","):
172 fields = entry.split("|")
173 if len(fields) <= max(allele_index, term_index): 173 ↛ 174line 173 didn't jump to line 174 because the condition on line 173 was never true
174 continue
175 if fields[allele_index] not in spellings: 175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true
176 continue
177 position = spellings.index(fields[allele_index])
178 terms.setdefault(position, []).extend(term for term in fields[term_index].split("&") if term)
179 return terms
181 def _consequence(self, term: str) -> OverlapConsequence:
182 """Return the catalogue's consequence for a term, or an unranked stand-in."""
183 rule = self.ruleset.by_term.get(term)
184 if rule is not None:
185 return rule.to_overlap_consequence()
186 return OverlapConsequence(term=term, accession="", rank=UNKNOWN_RANK, impact=None)
189def parser_for(path: str | Path, input_format: str | None = None) -> OutputParser:
190 """Return the reader for a file, by its declared format or its extension.
192 Raises:
193 ValueError: If the format is not one this package reads.
194 """
195 # Local imports: the seams import this module's base, and this is the one place all three meet.
196 # pylint: disable=import-outside-toplevel
197 from ensembl.vep.output.parser.json import JSONOutputParser
198 from ensembl.vep.output.parser.tab import TabOutputParser
200 name = str(path).lower()
201 if name.endswith(".gz"):
202 name = name[:-3]
203 chosen = input_format or name.rsplit(".", 1)[-1]
204 readers: dict[str, type[OutputParser]] = {
205 "vcf": VCFOutputParser,
206 "tab": TabOutputParser,
207 "txt": TabOutputParser,
208 "json": JSONOutputParser,
209 }
210 if chosen not in readers:
211 raise ValueError(f"no reader for {chosen!r} output; expected one of {sorted(readers)}")
212 return readers[chosen]()