Coverage for src/python/ensembl/vep/annotators/consequence/rules/editing.py: 86%

130 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"""Add and remove consequence catalogue entries. 

15 

16Never infer a ``when`` formula. An entry without one is marked for review because conformance tests 

17cannot detect a formula that every strategy evaluates consistently but incorrectly. 

18""" 

19 

20from __future__ import annotations 

21 

22import json 

23from collections.abc import Sequence 

24from typing import Any 

25 

26from ensembl.vep.annotators.consequence.facts.base import atom_names 

27from ensembl.vep.annotators.consequence.rules.catalogue import ACCESSION_PATTERN, ENTRY_KEY_ORDER 

28from ensembl.vep.annotators.consequence.rules.expressions import expr_from_json 

29 

30__all__ = [ 

31 "accession_index", 

32 "apply_add", 

33 "apply_remove", 

34 "build_entry", 

35 "derive_subsumes", 

36 "insert_at_rank", 

37 "next_rank", 

38 "remove_term", 

39 "resolve_when", 

40] 

41 

42 

43def accession_index(entries: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: 

44 """Build an accession -> entry lookup. 

45 

46 Args: 

47 entries (list[dict[str, Any]]): The catalogue's ``consequences`` list. 

48 

49 Returns: 

50 dict[str, dict[str, Any]]: Every entry, keyed by its SO accession. 

51 """ 

52 return {entry["accession"]: entry for entry in entries} 

53 

54 

55def derive_subsumes( 

56 so_parent_accessions: Sequence[str], entries_by_accession: dict[str, dict[str, Any]] 

57) -> tuple[tuple[str, ...], list[str]]: 

58 """Walk ``so_supported_parents`` transitively to propose a ``subsumes`` set. 

59 

60 Direction: if the new term A *is_a* an existing catalogue term B (B is one of A's SO parents), 

61 A is the more specific term, so A *subsumes* B -- suppressing B whenever A also fires. Walking 

62 stays inside the catalogue: an SO parent accession not represented here cannot be proposed 

63 (there is nothing to subsume), and a present-but-``when``-less ancestor (an EXCLUDED_TERMS-style 

64 term, see consequence/rules/catalogue.py) is skipped from the proposal itself -- it can never appear in a 

65 compiled FactRuleSet, so declaring a rule subsumes it would fail validation -- but is still 

66 noted, and its own further-up parents are still walked past it. 

67 

68 Args: 

69 so_parent_accessions (list[str]): The new term's immediate SO parent accessions. 

70 entries_by_accession (dict[str, dict[str, Any]]): accession -> catalogue entry lookup. 

71 

72 Returns: 

73 tuple[tuple[str, ...], list[str]]: The proposed, sorted ``subsumes`` term tuple, and a list 

74 of human-readable notes about the walk (skipped/unknown/excluded ancestors). 

75 """ 

76 subsumed_terms: set[str] = set() 

77 notes: list[str] = [] 

78 visited_accessions: set[str] = set() 

79 frontier = list(so_parent_accessions) 

80 

81 while frontier: 

82 accession = frontier.pop() 

83 if accession in visited_accessions: 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true

84 continue 

85 visited_accessions.add(accession) 

86 

87 entry = entries_by_accession.get(accession) 

88 if entry is None: 

89 notes.append(f"SO parent {accession} is not present in the catalogue -- skipped") 

90 continue 

91 

92 if entry.get("when") is not None: 

93 subsumed_terms.add(entry["term"]) 

94 else: 

95 notes.append( 

96 f"SO parent {entry['term']} ({accession}) has no 'when' in the catalogue -- not " 

97 "proposed as a subsumes target (it is never part of a compiled rule set), but its " 

98 "own SO parents are still walked" 

99 ) 

100 frontier.extend(entry.get("so_supported_parents", ())) 

101 

102 return tuple(sorted(subsumed_terms)), notes 

103 

104 

105def build_entry( 

106 *, 

107 term: str, 

108 accession: str, 

109 rank: int, 

110 tier: int, 

111 impact: str, 

112 so_supported_parents: Sequence[str], 

113 when: object | None, 

114 subsumes: tuple[str, ...], 

115 notes: str | None, 

116) -> dict[str, Any]: 

117 """Build a new catalogue entry dict in the canonical, round-trippable key order. 

118 

119 Args: 

120 term (str): The SO term name. 

121 accession (str): The SO accession. 

122 rank (int): Severity rank. 

123 tier (int): Tier grouping. 

124 impact (str): One of ConsequenceImpact's values. 

125 so_supported_parents (list[str]): SO parent accessions also represented in the catalogue. 

126 when (object | None): A compiled-and-validated ``when`` payload, or None for a needs-review 

127 placeholder (see resolve_when). 

128 subsumes (tuple[str, ...]): Term names this entry suppresses when it also fires. 

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

130 

131 Returns: 

132 dict[str, Any]: The new entry, with keys present/ordered exactly as an existing schema-4 

133 catalogue entry would have them (``when``/``subsumes``/``notes`` omitted, not 

134 null/empty, when absent). 

135 """ 

136 raw: dict[str, Any] = { 

137 "term": term, 

138 "accession": accession, 

139 "rank": rank, 

140 "tier": tier, 

141 "impact": impact, 

142 "so_supported_parents": list(so_supported_parents), 

143 } 

144 if when is not None: 

145 raw["when"] = when 

146 if subsumes: 146 ↛ 147line 146 didn't jump to line 147 because the condition on line 146 was never true

147 raw["subsumes"] = list(subsumes) 

148 if notes: 148 ↛ 149line 148 didn't jump to line 149 because the condition on line 148 was never true

149 raw["notes"] = notes 

150 return {key: raw[key] for key in ENTRY_KEY_ORDER if key in raw} 

151 

152 

153def next_rank(entries: list[dict[str, Any]]) -> int: 

154 """Return the rank one past the current highest rank. 

155 

156 Args: 

157 entries (list[dict[str, Any]]): The catalogue's ``consequences`` list. 

158 

159 Returns: 

160 int: ``max(rank for every entry) + 1``, or 1 if ``entries`` is empty. 

161 """ 

162 return max((int(entry.get("rank", 0)) for entry in entries), default=0) + 1 

163 

164 

165def insert_at_rank( 

166 entries: list[dict[str, Any]], new_entry: dict[str, Any], requested_rank: int | None 

167) -> list[dict[str, Any]]: 

168 """Insert ``new_entry`` at ``requested_rank``, shifting later ranks down to make room. 

169 

170 Args: 

171 entries (list[dict[str, Any]]): The catalogue's ``consequences`` list (not mutated). 

172 new_entry (dict[str, Any]): The entry to insert; its ``rank`` key is set by this function. 

173 requested_rank (int | None): The 1-based rank to insert at, or None to append after the 

174 current highest rank. 

175 

176 Returns: 

177 list[dict[str, Any]]: A new list, sorted by rank, with ``new_entry`` inserted and every 

178 colliding/later rank shifted up by one. 

179 

180 Raises: 

181 ValueError: If ``requested_rank`` is outside ``1..(current highest rank + 1)``. 

182 """ 

183 if requested_rank is None: 

184 new_entry["rank"] = next_rank(entries) 

185 return sorted([*entries, new_entry], key=lambda entry: int(entry["rank"])) 

186 

187 highest_rank = max((int(entry.get("rank", 0)) for entry in entries), default=0) 

188 if not 1 <= requested_rank <= highest_rank + 1: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true

189 raise ValueError(f"rank {requested_rank} out of range (1..{highest_rank + 1})") 

190 

191 shifted: list[dict[str, Any]] = [] 

192 for entry in entries: 

193 if int(entry.get("rank", 0)) >= requested_rank: 

194 entry = dict(entry) 

195 entry["rank"] = int(entry["rank"]) + 1 

196 shifted.append(entry) 

197 new_entry["rank"] = requested_rank 

198 return sorted([*shifted, new_entry], key=lambda entry: int(entry["rank"])) 

199 

200 

201def remove_term(entries: list[dict[str, Any]], term: str) -> tuple[list[dict[str, Any]], list[str]]: 

202 """Remove ``term``, clean up every other entry's ``subsumes``, and close the rank gap. 

203 

204 Args: 

205 entries (list[dict[str, Any]]): The catalogue's ``consequences`` list (not mutated). 

206 term (str): The term to remove. Caller has already verified it exists. 

207 

208 Returns: 

209 tuple[list[dict[str, Any]], list[str]]: The remaining entries (rank-sorted, gap closed), 

210 and the sorted list of terms whose ``subsumes`` referenced ``term`` and were cleaned. 

211 """ 

212 removed_entry = next(entry for entry in entries if entry["term"] == term) 

213 removed_rank = int(removed_entry.get("rank", 0)) 

214 

215 cleaned_from: list[str] = [] 

216 remaining: list[dict[str, Any]] = [] 

217 for entry in entries: 

218 if entry["term"] == term: 

219 continue 

220 entry = dict(entry) 

221 subsumes = entry.get("subsumes") 

222 if subsumes and term in subsumes: 222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true

223 entry["subsumes"] = [subsumed for subsumed in subsumes if subsumed != term] 

224 if not entry["subsumes"]: 

225 del entry["subsumes"] 

226 cleaned_from.append(entry["term"]) 

227 if int(entry.get("rank", 0)) > removed_rank: 

228 entry["rank"] = int(entry["rank"]) - 1 

229 remaining.append(entry) 

230 

231 remaining.sort(key=lambda entry: int(entry["rank"])) 

232 return remaining, sorted(cleaned_from) 

233 

234 

235def resolve_when(when_argument: str | None, known_atoms: list[str]) -> tuple[object | None, list[str], bool]: 

236 """Resolve ``--when`` into a validated payload, or a needs-review placeholder. 

237 

238 Args: 

239 when_argument (str | None): The raw ``--when`` JSON text, or None if not given. 

240 known_atoms (list[str]): Every registered fact atom name (ensembl.vep.annotators.consequence. 

241 facts.base.atom_names()), used to validate an explicit ``when``. 

242 

243 Returns: 

244 tuple[object | None, list[str], bool]: ``(when_payload, messages, needs_review)``. 

245 ``when_payload`` is a compiled-valid JSON payload if ``when_argument`` was given, else 

246 None. ``needs_review`` is True whenever ``when_payload`` is None. 

247 

248 Raises: 

249 ValueError: If ``when_argument`` is not valid JSON, does not compile to an expression, or 

250 references an atom name that is not registered. 

251 """ 

252 if when_argument is None: 

253 return None, ["no --when given; a formula has to be authored by hand"], True 

254 

255 try: 

256 when_payload = json.loads(when_argument) 

257 except json.JSONDecodeError as decode_error: 

258 raise ValueError(f"when is not valid JSON: {decode_error}") from decode_error 

259 

260 try: 

261 expression = expr_from_json(when_payload) 

262 except ValueError as compile_error: 

263 raise ValueError(f"when does not compile to an expression: {compile_error}") from compile_error 

264 

265 unknown_atoms = expression.atoms() - set(known_atoms) 

266 if unknown_atoms: 266 ↛ 267line 266 didn't jump to line 267 because the condition on line 266 was never true

267 raise ValueError(f"when references unknown fact atom(s): {sorted(unknown_atoms)}") 

268 

269 return when_payload, [f"using explicitly-authored --when: {json.dumps(when_payload)}"], False 

270 

271 

272def apply_add( 

273 payload: dict[str, Any], 

274 *, 

275 term: str, 

276 accession: str | None, 

277 impact: str | None, 

278 rank: int | None = None, 

279 tier: int = 3, 

280 so_parent: tuple[str, ...] = (), 

281 subsumes: tuple[str, ...] = (), 

282 no_derive_subsumes: bool = False, 

283 when: str | None = None, 

284 allow_missing_when: bool = False, 

285 notes: str | None = None, 

286) -> tuple[dict[str, Any], list[str]] | None: 

287 """Add a term to a catalogue payload, without writing anything. 

288 

289 Args: 

290 payload (dict[str, Any]): The payload to add to, mutated in place. 

291 term (str): The SO term to add. 

292 accession (str | None): Its SO accession. 

293 impact (str | None): Its impact bucket. 

294 rank (int | None): 1-based rank to insert at, or None to append after the highest. 

295 tier (int): Tier grouping. 

296 so_parent (tuple[str, ...]): SO parent accessions, used to derive ``subsumes``. 

297 subsumes (tuple[str, ...]): Extra terms to subsume, on top of the derived ones. 

298 no_derive_subsumes (bool): Skip deriving from ``so_parent``. 

299 when (str | None): The ``when`` payload as JSON, or None to write a placeholder. 

300 allow_missing_when (bool): Accept the placeholder rather than refusing. 

301 notes (str | None): Free-text notes. 

302 

303 Returns: 

304 tuple[dict[str, Any], list[str]] | None: ``(payload, messages)``, or None if the addition 

305 was rejected because no ``when`` was given and it was not explicitly allowed. 

306 

307 Raises: 

308 ValueError: On a usage error -- missing accession or impact, duplicate term or accession, 

309 unknown subsumes target, or a malformed accession. 

310 """ 

311 entries: list[dict[str, Any]] = payload["consequences"] 

312 

313 if accession is None or impact is None: 

314 raise ValueError("adding a term requires an accession and an impact") 

315 if not ACCESSION_PATTERN.match(accession): 

316 raise ValueError(f"accession {accession!r} does not look like SO:NNNNNNN") 

317 if any(entry["term"] == term for entry in entries): 

318 raise ValueError(f"catalogue already has a term named {term!r}") 

319 if any(entry["accession"] == accession for entry in entries): 

320 raise ValueError(f"catalogue already has an entry with accession {accession!r}") 

321 

322 known_terms = {entry["term"] for entry in entries} 

323 for target in subsumes: 

324 if target not in known_terms: 324 ↛ 323line 324 didn't jump to line 323 because the condition on line 324 was always true

325 raise ValueError(f"subsumes target {target!r} is not a catalogue term") 

326 

327 derived: tuple[str, ...] 

328 derive_notes: list[str] 

329 if no_derive_subsumes: 329 ↛ 330line 329 didn't jump to line 330 because the condition on line 329 was never true

330 derived, derive_notes = (), [] 

331 else: 

332 derived, derive_notes = derive_subsumes(so_parent, accession_index(entries)) 

333 final_subsumes = tuple(dict.fromkeys((*derived, *subsumes))) 

334 

335 when_payload, when_messages, needs_review = resolve_when(when, atom_names()) 

336 

337 messages = [ 

338 f"deriving subsumes for {term!r} from {len(so_parent)} SO parent accession(s)", 

339 *derive_notes, 

340 f"derived subsumes: {list(derived)}", 

341 f"final subsumes (derived + explicit): {list(final_subsumes)}", 

342 *when_messages, 

343 ] 

344 

345 if needs_review and not allow_missing_when: 

346 banner = "!" * 78 

347 messages.append( 

348 f"\n{banner}\n" 

349 "NEEDS REVIEW: no --when was given and none can be safely inferred.\n" 

350 "A boolean formula cannot be reliably inferred from a term name alone -- a wrong guess\n" 

351 "would pass conformance (every annotator agrees on the same wrong answer) and only show\n" 

352 "up as bad biology later. Author the `when` by hand and re-run with --when, or\n" 

353 "acknowledge the placeholder explicitly with --allow-missing-when.\n" 

354 f"{banner}" 

355 ) 

356 for message in messages: 

357 print(message) 

358 return None 

359 

360 new_entry = build_entry( 

361 term=term, 

362 accession=accession, 

363 rank=0, 

364 tier=tier, 

365 impact=impact, 

366 so_supported_parents=so_parent, 

367 when=when_payload, 

368 subsumes=final_subsumes, 

369 notes=notes, 

370 ) 

371 payload["consequences"] = insert_at_rank(entries, new_entry, rank) 

372 return payload, messages 

373 

374 

375def apply_remove(payload: dict[str, Any], *, term: str) -> tuple[dict[str, Any], list[str]]: 

376 """Remove a term from a catalogue payload, without writing anything. 

377 

378 Args: 

379 payload (dict[str, Any]): The payload to remove from, mutated in place. 

380 term (str): The SO term to remove. 

381 

382 Returns: 

383 tuple[dict[str, Any], list[str]]: ``(payload, messages)``. Removal is never a needs-review 

384 case, so unlike ``apply_add`` this always succeeds when the term exists. 

385 

386 Raises: 

387 ValueError: If no entry named ``term`` exists. 

388 """ 

389 entries: list[dict[str, Any]] = payload["consequences"] 

390 if not any(entry["term"] == term for entry in entries): 

391 raise ValueError(f"no catalogue entry named {term!r}") 

392 

393 remaining, cleaned_from = remove_term(entries, term) 

394 messages = [f"removed {term!r}"] 

395 if cleaned_from: 395 ↛ 396line 395 didn't jump to line 396 because the condition on line 395 was never true

396 messages.append(f"removed {term!r} from the 'subsumes' list of: {cleaned_from}") 

397 else: 

398 messages.append(f"{term!r} was not subsumed by any other entry -- no cleanup needed") 

399 

400 payload["consequences"] = remaining 

401 return payload, messages