Coverage for src/python/ensembl/vep/output/factory/stream/json.py: 97%

123 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"""Ensembl VEP JSON-schema record generation.""" 

15 

16from __future__ import annotations 

17 

18import re 

19from collections.abc import Iterable, Iterator 

20from typing import cast 

21 

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

23from ensembl.vep.output.factory.base import AnnotatedVariant, AnnotationRecord 

24 

25__all__ = ["JSONStreamFactory"] 

26 

27_FEATURE_GROUPS = { 

28 "Transcript": "transcript_consequences", 

29 "RegulatoryFeature": "regulatory_feature_consequences", 

30 "MotifFeature": "motif_feature_consequences", 

31 "Intergenic": "intergenic_consequences", 

32} 

33_CORE_FIELD_NAMES = { 

34 "Allele": "variant_allele", 

35 "Amino_acids": "amino_acids", 

36 "BIOTYPE": "biotype", 

37 "Codons": "codons", 

38 "Consequence": "consequence_terms", 

39 "DISTANCE": "distance", 

40 "EXON": "exon", 

41 "Existing_variation": "existing_variation", 

42 "Feature": "feature_id", 

43 "Gene": "gene_id", 

44 "HGNC_ID": "hgnc_id", 

45 "IMPACT": "impact", 

46 "INTRON": "intron", 

47 "OVERLAPBP": "bp_overlap", 

48 "OVERLAPPC": "percentage_overlap", 

49 "PICK": "pick", 

50 "REFSEQ": "refseq_transcript_ids", 

51 "REF_ALLELE": "ref_allele", 

52 "STRAND": "strand", 

53 "SYMBOL": "gene_symbol", 

54 "SYMBOL_SOURCE": "gene_symbol_source", 

55 "ENSP": "protein_id", 

56} 

57_POSITION_FIELD_NAMES = { 

58 "cDNA_position": "cdna", 

59 "CDS_position": "cds", 

60 "Protein_position": "protein", 

61} 

62_SKIPPED_FIELDS = frozenset({"Feature_type", "Location", "Uploaded_variation", "VARIANT_CLASS"}) 

63_NUMBERIFY_EXEMPT = frozenset( 

64 { 

65 "seq_region_name", 

66 "id", 

67 "gene_id", 

68 "gene_symbol", 

69 "transcript_id", 

70 "SYMBOL", 

71 } 

72) 

73_PREDICTION_PATTERN = re.compile( 

74 r"(?:(?P<prediction>[A-Za-z_]+)(?:\((?P<score>[\d.]+)\))?|(?P<score_only>[\d.]+))" 

75) 

76 

77 

78class JSONStreamFactory: 

79 """Ensembl VEP JSON-schema record factory.""" 

80 

81 def records(self, variants: Iterable[AnnotatedVariant]) -> Iterator[dict[str, object]]: 

82 """Yield each variant as a JSON-compatible dictionary.""" 

83 for variant in variants: 83 ↛ exitline 83 didn't return from function 'records' because the loop on line 83 didn't complete

84 yield self.record(variant) 

85 

86 def record(self, variant: AnnotatedVariant) -> dict[str, object]: 

87 """Return one Ensembl VEP JSON-schema dictionary.""" 

88 record: dict[str, object] = { 

89 "id": variant.id, 

90 "seq_region_name": variant.seq_region_name, 

91 "start": variant.start, 

92 "end": variant.end, 

93 "strand": variant.strand, 

94 "allele_string": variant.allele_string, 

95 "assembly_name": variant.assembly_name, 

96 "most_severe_consequence": variant.most_severe_consequence or UNKNOWN_VALUE, 

97 } 

98 if variant.input_columns: 

99 record["input"] = "\t".join(variant.input_columns) 

100 if variant.variant_class is not None: 

101 record["variant_class"] = variant.variant_class 

102 if variant.skipped: 

103 return {"input": record.get("input", "")} 

104 

105 grouped_annotations: dict[str, list[dict[str, object]]] = {} 

106 for annotation in variant.annotations: 

107 feature_type = annotation.get("Feature_type") 

108 group_name = _FEATURE_GROUPS.get(str(feature_type)) 

109 if feature_type is None: 

110 group_name = "intergenic_consequences" 

111 if group_name is None: 

112 continue 

113 grouped_annotations.setdefault(group_name, []).append(self._annotation(annotation)) 

114 record.update(grouped_annotations) 

115 return cast(dict[str, object], self._numberify(record)) 

116 

117 def _annotation(self, annotation: AnnotationRecord) -> dict[str, object]: 

118 """Convert one output hash to its nested JSON representation.""" 

119 converted: dict[str, object] = {} 

120 feature_type = annotation.get("Feature_type") 

121 for name, value in annotation.items(): 

122 if name in _SKIPPED_FIELDS or self._empty(name, value): 

123 continue 

124 if name in _POSITION_FIELD_NAMES: 

125 self._add_position(converted, _POSITION_FIELD_NAMES[name], value) 

126 continue 

127 json_name = _CORE_FIELD_NAMES.get(name, name.lower()) 

128 if name == "Feature": 

129 json_name = self._feature_name(feature_type) 

130 converted[json_name] = 1 if value == "YES" else value 

131 self._split_predictions(converted) 

132 self._structure_domains(converted) 

133 return converted 

134 

135 @staticmethod 

136 def _split_predictions(record: dict[str, object]) -> None: 

137 """Split SIFT and PolyPhen values into prediction and score fields.""" 

138 for tool in ("sift", "polyphen"): 

139 value = record.pop(tool, None) 

140 if value is None: 

141 continue 

142 match = _PREDICTION_PATTERN.fullmatch(str(value)) 

143 if match is None: 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true

144 continue 

145 prediction = match.group("prediction") 

146 score = match.group("score") or match.group("score_only") 

147 if prediction: 

148 record[f"{tool}_prediction"] = prediction 

149 if score is not None: 149 ↛ 138line 149 didn't jump to line 138 because the condition on line 149 was always true

150 record[f"{tool}_score"] = score 

151 

152 @staticmethod 

153 def _structure_domains(record: dict[str, object]) -> None: 

154 """Convert domain names into Ensembl VEP's database/name objects.""" 

155 domains = record.get("domains") 

156 if not isinstance(domains, (list, tuple)): 

157 return 

158 structured = [] 

159 for domain in domains: 

160 database, separator, name = str(domain).partition(":") 

161 if separator and database and name: 

162 structured.append({"db": database, "name": name}) 

163 record["domains"] = structured 

164 

165 @staticmethod 

166 def _feature_name(feature_type: object) -> str: 

167 """Return the JSON identifier name for one feature type.""" 

168 if feature_type == "Transcript": 

169 return "transcript_id" 

170 if feature_type == "RegulatoryFeature": 

171 return "regulatory_feature_id" 

172 if feature_type == "MotifFeature": 

173 return "motif_feature_id" 

174 return "feature_id" 

175 

176 @staticmethod 

177 def _empty(name: str, value: object) -> bool: 

178 """Return whether a field is absent from Perl VEP JSON output.""" 

179 return value is None or value == "" or (name != "Allele" and value == EMPTY_ALLELE) 

180 

181 @staticmethod 

182 def _add_position(record: dict[str, object], prefix: str, value: object) -> None: 

183 """Add one VEP position field as JSON start and end fields.""" 

184 position = str(value) 

185 start, separator, end = position.partition("-") 

186 start_value = JSONStreamFactory._position_value(start) 

187 end_value = JSONStreamFactory._position_value(end if separator else start) 

188 if start_value is not None: 

189 record[f"{prefix}_start"] = start_value 

190 if end_value is not None: 190 ↛ exitline 190 didn't return from function '_add_position' because the condition on line 190 was always true

191 record[f"{prefix}_end"] = end_value 

192 

193 @staticmethod 

194 def _position_value(value: str) -> int | str | None: 

195 """Return a numeric coordinate or a VEP position-with-total string.""" 

196 if value.isdigit(): 

197 return int(value) 

198 position, separator, total = value.partition("/") 

199 if separator and position.isdigit() and total.isdigit(): 

200 return value 

201 return None 

202 

203 @classmethod 

204 def _numberify(cls, value: object, *, key: str | None = None) -> object: 

205 """Recursively convert numeric strings as Ensembl VEP JSON does.""" 

206 if isinstance(value, dict): 

207 return {name: cls._numberify(item, key=name) for name, item in value.items()} 

208 if isinstance(value, (list, tuple)): 

209 return [cls._numberify(item) for item in value] 

210 if key in _NUMBERIFY_EXEMPT or not isinstance(value, str): 

211 return value 

212 try: 

213 return int(value) 

214 except ValueError: 

215 try: 

216 return float(value) 

217 except ValueError: 

218 return value