Coverage for src/python/ensembl/vep/output/factory/write/vcf.py: 97%

98 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"""VCF output: the input line back, with a ``CSQ`` INFO field of pipe-separated consequences. 

15 

16A port of Perl VEP's ``OutputFactory/VCF.pm``. A snapshot's original VCF line is written back with 

17any previous ``CSQ`` replaced. Each selected (allele, feature) record becomes one comma-separated 

18chunk whose fields follow the ``Format`` the header declares -- which is exactly what 

19``output/parser/vcf.py`` reads back. 

20 

21A snapshot that did not come from a VCF line carries no columns, and VCF cannot invent them: an 

22indel's spelling needs reference bases, which a detached snapshot deliberately does not hold. So 

23whoever builds such a snapshot supplies the columns, with the padding rule 

24``corpus/exporter/formats/file/vcf.py`` uses; writing one without them is refused rather than 

25guessed at. 

26""" 

27 

28from __future__ import annotations 

29 

30import re 

31from collections.abc import Sequence 

32from datetime import datetime 

33 

34from attrs import define, field 

35 

36from ensembl.vep import __version__ 

37from ensembl.vep.common.constants import EMPTY_ALLELE 

38from ensembl.vep.common.methods import reverse_complement 

39from ensembl.vep.output.factory.base import AnnotatedVariant, AnnotatedVariantFactory 

40 

41__all__ = ["DEFAULT_INFO_FIELD", "VCF_COLS", "VCFOutputWriter"] 

42 

43VCF_COLS = ( 

44 "Allele", 

45 "Consequence", 

46 "IMPACT", 

47 "SYMBOL", 

48 "Gene", 

49 "Feature_type", 

50 "Feature", 

51 "BIOTYPE", 

52 "EXON", 

53 "INTRON", 

54 "HGVSc", 

55 "HGVSp", 

56 "cDNA_position", 

57 "CDS_position", 

58 "Protein_position", 

59 "Amino_acids", 

60 "Codons", 

61 "Existing_variation", 

62) 

63"""The ``CSQ`` fields VEP writes by default, in its order.""" 

64 

65DEFAULT_INFO_FIELD = "CSQ" 

66FILEFORMAT = "##fileformat=VCFv4.1" 

67COLUMN_HEADING = "#" + "\t".join(("CHROM", "POS", "ID", "REF", "ALT", "QUAL", "FILTER", "INFO")) 

68_INFO_COLUMN = 7 

69 

70 

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

72class VCFOutputWriter: 

73 """VCF serializer for annotated-variant snapshots. 

74 

75 Attributes: 

76 records (AnnotatedVariantFactory): The factory whose flags the declared ``Format`` must 

77 describe, so a reader of the header finds the fields the records actually carry. 

78 info_field (str): The INFO key consequences are written under. 

79 keep_csq (bool): Keep a ``CSQ`` already on the input line, and its header, instead of 

80 replacing them. 

81 command_line (str): The command written into the header. 

82 time (str | None): The timestamp written into the header, or None for now. 

83 """ 

84 

85 records: AnnotatedVariantFactory = field(factory=AnnotatedVariantFactory) 

86 info_field: str = field(default=DEFAULT_INFO_FIELD) 

87 keep_csq: bool = field(default=False) 

88 command_line: str = field(default="") 

89 time: str | None = field(default=None) 

90 

91 @property 

92 def version(self) -> str: 

93 """Return the version written into the header.""" 

94 return __version__ 

95 

96 def timestamp(self) -> str: 

97 """Return the header timestamp, formatted as VEP formats it.""" 

98 return self.time if self.time is not None else datetime.now().strftime("%Y-%m-%d %H:%M:%S") 

99 

100 def fields(self) -> list[str]: 

101 """Return the fields each chunk carries: VEP's defaults, then what the flags add.""" 

102 fields = list(VCF_COLS) 

103 for name in self.records.flag_fields(): 

104 if name not in fields: 

105 fields.append(name) 

106 return fields 

107 

108 def headers(self, input_headers: Sequence[str] = ()) -> list[str]: 

109 """Return the header lines, carrying the input file's own when there are any. 

110 

111 Args: 

112 input_headers (Sequence[str]): The input VCF's header lines, column heading last. 

113 

114 Returns: 

115 list[str]: The meta lines, then VEP's own, then the column heading. 

116 """ 

117 headers: list[str] = [] 

118 if input_headers: 

119 if not any(line.lower().startswith("##fileformat=vcfv4") for line in input_headers): 

120 headers.append(FILEFORMAT) 

121 info_declaration = re.compile(rf"ID={re.escape(self.info_field)},", re.IGNORECASE) 

122 for line in input_headers: 

123 if self.keep_csq or not (info_declaration.search(line) or line.startswith("##VEP")): 

124 headers.append(line) 

125 column_heading = headers.pop() 

126 else: 

127 headers.append(FILEFORMAT) 

128 column_heading = COLUMN_HEADING 

129 

130 headers.append(f'##VEP="v{self.version}" time="{self.timestamp()}"') 

131 headers.append( 

132 f"##INFO=<ID={self.info_field},Number=.,Type=String," 

133 f'Description="Consequence annotations from Ensembl VEP. Format: {"|".join(self.fields())}">' 

134 ) 

135 if self.command_line: 

136 headers.append(f"##VEP-command-line='{self.command_line}'") 

137 headers.append(column_heading) 

138 return headers 

139 

140 def line(self, variant: AnnotatedVariant) -> str: 

141 """Return one annotated VCF record.""" 

142 columns = self._columns(variant) 

143 info = "" if columns[_INFO_COLUMN] in {"", "."} else columns[_INFO_COLUMN] 

144 chunks = [self.info_chunk(annotation, variant.strand) for annotation in variant.annotations] 

145 if chunks: 

146 info = f"{info};" if info else "" 

147 info += f"{self.info_field}={','.join(chunks)}" 

148 columns[_INFO_COLUMN] = info or "." 

149 return "\t".join(columns) 

150 

151 def info_chunk(self, output_hash: dict[str, object], strand: int = 1) -> str: 

152 """Encode one output hash as a pipe-separated chunk. 

153 

154 The escaping is VEP's: the characters VCF reserves inside INFO -- ``,`` ``;`` ``|`` and 

155 whitespace -- are replaced so a chunk can never split, and ``-`` means empty in every field 

156 but ``Allele``. A zero is kept rather than blanked. 

157 """ 

158 chunk = [] 

159 for column in self.fields(): 

160 value = output_hash.get(column) 

161 if value is None or value == "": 

162 chunk.append("") 

163 continue 

164 if not isinstance(value, (list, tuple)) and str(value) == "0": 

165 chunk.append("0") 

166 continue 

167 

168 data = "&".join(str(item) for item in value) if isinstance(value, (list, tuple)) else str(value) 

169 if column == "Allele": 

170 if strand < 0 and data != EMPTY_ALLELE: 

171 data = reverse_complement(data) 

172 elif data == EMPTY_ALLELE: 

173 data = "" 

174 if column == "SYMBOL": 174 ↛ 175line 174 didn't jump to line 175 because the condition on line 174 was never true

175 data = re.sub(r"\s", "%20", data) 

176 data = data.replace(",", "&").replace(";", "%3B") 

177 data = re.sub(r"\s+", "_", data) 

178 chunk.append(data.replace("|", "&")) 

179 return "|".join(chunk) 

180 

181 def prepare_input_columns(self, record_columns: Sequence[str]) -> list[str]: 

182 """Copy input columns and remove an annotation field scheduled for replacement.""" 

183 columns = [str(column) for column in record_columns] 

184 while len(columns) <= _INFO_COLUMN: 184 ↛ 185line 184 didn't jump to line 185 because the condition on line 184 was never true

185 columns.append(".") 

186 info = "" if columns[_INFO_COLUMN] in {"", "."} else columns[_INFO_COLUMN] 

187 key = re.escape(self.info_field) 

188 if not self.keep_csq and re.search(rf"(^|;){key}=", info): 

189 info = re.sub(rf"(^|;){key}=\S+?(;\S|$)", r"\2", info, count=1) 

190 info = info.removeprefix(";") 

191 columns[_INFO_COLUMN] = info or "." 

192 return columns 

193 

194 def _columns(self, variant: AnnotatedVariant) -> list[str]: 

195 """Return input columns ready for a replacement annotation field.""" 

196 if variant.input_columns: 

197 return self.prepare_input_columns(variant.input_columns) 

198 raise ValueError("VCF output requires the original input columns")