Coverage for src/python/ensembl/vep/annotators/consequence/rules/catalogue.py: 97%

63 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"""Load the checked-in overlap consequence catalogue (``data/overlap_consequences.json``). 

15 

16The catalogue is the shared source of term, accession, rank, tier, impact, formula, subsumption, 

17and ontology-parent metadata. ``when`` uses fact names and nested ``not``, ``all``, and ``any`` 

18expressions. ``subsumes`` declares terms suppressed when both rules fire, while 

19``so_supported_parents`` records represented Sequence Ontology parents. 

20 

21Fallback terms listed in ``EXCLUDED_TERMS`` intentionally have no ``when`` formula. All other 

22applicability conditions, including feature-kind checks, remain explicit in catalogue formulas. 

23""" 

24 

25from __future__ import annotations 

26 

27import hashlib 

28import json 

29import re 

30from dataclasses import dataclass, field 

31from functools import cache 

32from importlib.resources import files 

33from pathlib import Path 

34from typing import Any 

35 

36from ensembl.vep.common import ConsequenceImpact 

37 

38__all__ = [ 

39 "ACCESSION_PATTERN", 

40 "CATALOGUE_RESOURCE", 

41 "ConsequenceDefinition", 

42 "DEFAULT_TERM", 

43 "ENTRY_KEY_ORDER", 

44 "EXCLUDED_TERMS", 

45 "SUPPORTED_SCHEMA_VERSIONS", 

46 "catalogue_digest", 

47 "catalogue_path", 

48 "dump_catalogue", 

49 "load_catalogue", 

50 "load_consequence_definitions", 

51] 

52 

53CATALOGUE_RESOURCE = "data/overlap_consequences.json" 

54SUPPORTED_SCHEMA_VERSIONS = (5,) 

55 

56ACCESSION_PATTERN = re.compile(r"^SO:\d{7}$") 

57"""Shape of a Sequence Ontology accession, e.g. ``SO:0001627``.""" 

58 

59ENTRY_KEY_ORDER = ( 

60 "term", 

61 "accession", 

62 "rank", 

63 "tier", 

64 "impact", 

65 "so_supported_parents", 

66 "when", 

67 "subsumes", 

68 "notes", 

69) 

70"""Canonical per-entry key order, matching every existing schema-5 entry, so a freshly built entry 

71round-trips identically to a hand-edited one.""" 

72 

73DEFAULT_TERM = "intergenic_variant" 

74"""Fallback term applied by an annotator's caller when nothing else matched.""" 

75 

76EXCLUDED_TERMS = frozenset( 

77 { 

78 "intergenic_variant", 

79 "sequence_variant", 

80 } 

81) 

82"""Catalogue terms with no ``when`` documented.""" 

83 

84 

85@dataclass(frozen=True) 

86class ConsequenceDefinition: 

87 """Represent one parsed entry from the overlap consequence catalogue. 

88 

89 Attributes: 

90 term (str): The SO term, e.g. "missense_variant". 

91 accession (str): The SO accession, e.g. "SO:0001583". 

92 rank (int): Severity rank; 1 is most severe. 

93 tier (int): Tier grouping used by VEP's own evaluation order. 

94 impact (ConsequenceImpact | None): The IMPACT rating. 

95 when (object | None): A JSON boolean expression over fact atom names or None if this term 

96 is on EXCLUDED_TERMS. 

97 subsumes (tuple[str, ...]): Term names this consequence suppresses when when evaluated as true. 

98 so_supported_parents (tuple[str, ...]): SO ontology parent accessions that are also 

99 represented in this catalogue. 

100 notes (str | None): Free-text notes, if any. 

101 """ 

102 

103 term: str 

104 accession: str 

105 rank: int 

106 tier: int 

107 impact: ConsequenceImpact | None 

108 when: object | None 

109 subsumes: tuple[str, ...] = field(default_factory=tuple) 

110 so_supported_parents: tuple[str, ...] = field(default_factory=tuple) 

111 notes: str | None = None 

112 

113 

114def catalogue_path() -> Path: 

115 """Return the filesystem path of the packaged catalogue. 

116 

117 Resolved as a package resource rather than relative to this file, so it survives being 

118 installed. Writing to it is refused unless the caller asks for it explicitly -- see 

119 ensembl.vep.annotators.consequence.rules.editing. 

120 """ 

121 resource = files("ensembl.vep.annotators.consequence").joinpath(CATALOGUE_RESOURCE) 

122 return Path(str(resource)) 

123 

124 

125def load_catalogue(path: Path | None = None) -> dict[str, Any]: 

126 """Return a catalogue's raw JSON payload, for editing rather than evaluation. 

127 

128 ``load_consequence_definitions`` is the counterpart that parses the payload into rules; this 

129 keeps every key, including any the schema has that the parser ignores. 

130 

131 Args: 

132 path (Path | None): The catalogue to read, or None for the packaged one. 

133 

134 Returns: 

135 dict[str, Any]: The payload as parsed from JSON. 

136 

137 Raises: 

138 ValueError: If the payload's ``schema_version`` is unsupported. 

139 """ 

140 source = path or catalogue_path() 

141 payload = json.loads(source.read_text(encoding="utf-8")) 

142 schema_version = payload.get("schema_version") 

143 if schema_version not in SUPPORTED_SCHEMA_VERSIONS: 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true

144 raise ValueError( 

145 f"Unsupported overlap consequence catalogue schema version: {schema_version!r} " 

146 f"(supported: {SUPPORTED_SCHEMA_VERSIONS})" 

147 ) 

148 return payload 

149 

150 

151def dump_catalogue(payload: dict[str, Any]) -> str: 

152 """Return a catalogue payload as JSON text, in the checked-in formatting.""" 

153 return json.dumps(payload, indent=4) + "\n" 

154 

155 

156@cache 

157def load_consequence_definitions() -> tuple[ConsequenceDefinition, ...]: 

158 """Load and parse the package consequence catalogue. 

159 

160 Returns: 

161 tuple[ConsequenceDefinition, ...]: Every catalogue entry, sorted by ``(rank, term)``. 

162 

163 Raises: 

164 ValueError: If the catalogue's ``schema_version`` is unsupported, or a term appears more 

165 than once. 

166 """ 

167 resource = files("ensembl.vep.annotators.consequence").joinpath(CATALOGUE_RESOURCE) 

168 payload = json.loads(resource.read_text(encoding="utf-8")) 

169 schema_version = payload.get("schema_version") 

170 if schema_version not in SUPPORTED_SCHEMA_VERSIONS: 

171 raise ValueError( 

172 f"Unsupported overlap consequence catalogue schema version: {schema_version!r} " 

173 f"(supported: {SUPPORTED_SCHEMA_VERSIONS})" 

174 ) 

175 

176 definitions: list[ConsequenceDefinition] = [] 

177 seen_terms: set[str] = set() 

178 

179 for entry in payload["consequences"]: 

180 term = entry["term"] 

181 if term in seen_terms: 

182 raise ValueError(f"Duplicate consequence catalogue term: {term}") 

183 seen_terms.add(term) 

184 

185 definitions.append( 

186 ConsequenceDefinition( 

187 term=term, 

188 accession=entry["accession"], 

189 rank=int(entry.get("rank", 0)), 

190 tier=int(entry.get("tier", 0)), 

191 impact=ConsequenceImpact(entry["impact"]) if entry.get("impact") else None, 

192 when=entry.get("when"), 

193 subsumes=tuple(entry.get("subsumes", ())), 

194 so_supported_parents=tuple(entry.get("so_supported_parents", ())), 

195 notes=entry.get("notes"), 

196 ) 

197 ) 

198 

199 return tuple(sorted(definitions, key=lambda definition: (definition.rank, definition.term))) 

200 

201 

202def catalogue_digest(path: Path | None = None) -> str: 

203 """Return a short digest of a catalogue file's bytes, the packaged catalogue by default. 

204 

205 What a frozen expectation records beside its terms, so a later mismatch can be told apart: 

206 the catalogue changed under it, or the annotator did. 

207 """ 

208 source = path if path is not None else catalogue_path() 

209 return hashlib.sha256(source.read_bytes()).hexdigest()[:16]