Coverage for src/python/ensembl/vep/corpus/golden/terms.py: 92%
99 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"""Frozen expected terms emitted for a corpus and pinned to a file.
16Conformance proves every annotator agrees with ``consequence.linear``. It cannot catch all of them
17agreeing on the same wrong answer; a golden file can. It freezes the terms one annotator produced
18for one corpus, together with the corpus spec and the catalogue that produced them, so a later run
19is checked against a fixed expectation rather than only against itself.
21Named ``golden`` on purpose: in this repository "oracle" already means the external Perl
22``VariationEffect.pm``, whose whole value is that it is *not* us. This is the opposite thing.
24A mismatch is reported three distinct ways, because each calls for a different response. The
25catalogue changed under the file -- regenerate it, deliberately. The file was recorded for another
26corpus -- it is the wrong file. Or the terms moved with neither changed -- a regression.
27"""
29from __future__ import annotations
31import json
32from pathlib import Path
34from attrs import field, frozen
36from ensembl.vep.annotators.base import Annotator
37from ensembl.vep.annotators.consequence.rules.catalogue import catalogue_digest
38from ensembl.vep.corpus.base import Corpus
39from ensembl.vep.corpus.spec import CorpusSpec
40from ensembl.vep.models.overlap import OverlapConsequence, TranscriptVariationAllele
42__all__ = ["FORMAT_VERSION", "GoldenReport", "GoldenTerms", "overlap_key", "record_golden"]
44FORMAT_VERSION = 1
45"""Bumped whenever the file layout changes, so an old file is rejected rather than misread."""
47_REPORT_LIMIT = 20
50def overlap_key(name: str, overlap: TranscriptVariationAllele) -> str:
51 """Return the key an overlap is filed under: its feature, then its variant's name.
53 A name identifies the variant, not the overlap -- one variant pairs with every feature in its
54 flank window -- so the feature has to be part of the key.
55 """
56 return f"{overlap.feature.stable_id}::{name}"
59@frozen(kw_only=True, auto_attribs=True)
60class GoldenTerms:
61 """The terms one annotator emitted for every overlap of one corpus.
63 Attributes:
64 spec (CorpusSpec): The corpus the terms were recorded over.
65 annotator (str): The annotator that emitted them.
66 catalogue (str): Digest of the catalogue they were emitted against.
67 terms (dict[str, tuple[str, ...]]): ``feature::name`` -> the emitted terms, in order.
68 """
70 spec: CorpusSpec
71 annotator: str
72 catalogue: str
73 terms: dict[str, tuple[str, ...]] = field(factory=dict)
75 def to_json(self) -> str:
76 """Return the file text: a header, then one overlap per line.
78 One line per overlap is deliberate. Regenerating after a catalogue change then diffs as
79 exactly the overlaps whose terms moved, which is the review a regeneration needs.
80 """
81 header = {
82 "format_version": FORMAT_VERSION,
83 "spec": self.spec.as_dict(),
84 "annotator": self.annotator,
85 "catalogue": self.catalogue,
86 }
87 lines = ["{"]
88 for name, value in header.items():
89 lines.append(f" {json.dumps(name)}: {json.dumps(value, sort_keys=True)},")
90 lines.append(' "terms": {')
91 entries = sorted(self.terms.items())
92 for index, (key, value) in enumerate(entries):
93 separator = "," if index < len(entries) - 1 else ""
94 lines.append(f" {json.dumps(key)}: {json.dumps(list(value))}{separator}")
95 lines.append(" }")
96 lines.append("}")
97 return "\n".join(lines) + "\n"
99 @classmethod
100 def from_json(cls, text: str) -> GoldenTerms:
101 """Read terms back from file text.
103 Raises:
104 ValueError: If the file was written in a different format version.
105 """
106 payload = json.loads(text)
107 version = payload.get("format_version")
108 if version != FORMAT_VERSION:
109 raise ValueError(f"golden file format {version!r} is not the supported {FORMAT_VERSION}")
110 terms = {key: tuple(value) for key, value in payload["terms"].items()}
111 return cls(
112 spec=CorpusSpec.from_dict(payload["spec"]),
113 annotator=payload["annotator"],
114 catalogue=payload["catalogue"],
115 terms=terms,
116 )
118 def write(self, path: Path) -> None:
119 """Write the terms to a file, creating its directory if needed."""
120 path.parent.mkdir(parents=True, exist_ok=True)
121 path.write_text(self.to_json(), encoding="utf-8")
123 @classmethod
124 def load(cls, path: Path) -> GoldenTerms:
125 """Read terms from a file."""
126 return cls.from_json(path.read_text(encoding="utf-8"))
129def record_golden(
130 corpus: Corpus, annotator: Annotator[OverlapConsequence], annotator_name: str
131) -> GoldenTerms:
132 """Annotate every overlap of a corpus and freeze the terms.
134 Args:
135 corpus (Corpus): The corpus to record over.
136 annotator (Annotator[OverlapConsequence]): The annotator whose terms are frozen.
137 annotator_name (str): Its registry name, recorded in the file.
139 Returns:
140 GoldenTerms: The frozen terms.
142 Raises:
143 ValueError: If two overlaps would be filed under the same key.
144 """
145 named_overlaps = list(corpus.named_overlaps)
146 results = annotator.annotate_feature_overlaps([overlap for _name, overlap in named_overlaps])
147 terms: dict[str, tuple[str, ...]] = {}
148 for (name, overlap), consequences in zip(named_overlaps, results, strict=True):
149 key = overlap_key(name, overlap)
150 if key in terms: 150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true
151 raise ValueError(f"two overlaps share the key {key!r}; a golden file needs them unique")
152 terms[key] = tuple(consequence.term for consequence in consequences)
153 return GoldenTerms(spec=corpus.spec, annotator=annotator_name, catalogue=catalogue_digest(), terms=terms)
156@frozen(kw_only=True, auto_attribs=True)
157class GoldenReport:
158 """How recorded terms differ from golden ones.
160 Attributes:
161 catalogue_changed (bool): The catalogue is not the one the golden file was recorded against.
162 spec_changed (bool): The corpus is not the one the golden file was recorded over.
163 annotator_changed (bool): A different annotator produced the recording. Informational --
164 checking another strategy against one annotator's golden file is a legitimate use.
165 missing (tuple[str, ...]): Keys the golden file has and the recording does not.
166 unexpected (tuple[str, ...]): Keys the recording has and the golden file does not.
167 mismatches (tuple[tuple[str, tuple[str, ...], tuple[str, ...]], ...]): Key, golden terms,
168 recorded terms, for every overlap whose terms moved.
169 """
171 catalogue_changed: bool = field(default=False)
172 spec_changed: bool = field(default=False)
173 annotator_changed: bool = field(default=False)
174 missing: tuple[str, ...] = field(default=())
175 unexpected: tuple[str, ...] = field(default=())
176 mismatches: tuple[tuple[str, tuple[str, ...], tuple[str, ...]], ...] = field(default=())
178 @classmethod
179 def compare(cls, golden: GoldenTerms, recorded: GoldenTerms) -> GoldenReport:
180 """Compare a recording against golden terms."""
181 golden_keys = set(golden.terms)
182 recorded_keys = set(recorded.terms)
183 mismatches = []
184 for key in sorted(golden_keys & recorded_keys):
185 if golden.terms[key] != recorded.terms[key]:
186 mismatches.append((key, golden.terms[key], recorded.terms[key]))
187 return cls(
188 catalogue_changed=golden.catalogue != recorded.catalogue,
189 spec_changed=golden.spec != recorded.spec,
190 annotator_changed=golden.annotator != recorded.annotator,
191 missing=tuple(sorted(golden_keys - recorded_keys)),
192 unexpected=tuple(sorted(recorded_keys - golden_keys)),
193 mismatches=tuple(mismatches),
194 )
196 @property
197 def ok(self) -> bool:
198 """Whether the recording matches, against the same catalogue and corpus."""
199 return not (
200 self.catalogue_changed or self.spec_changed or self.missing or self.unexpected or self.mismatches
201 )
203 def lines(self, limit: int = _REPORT_LIMIT) -> list[str]:
204 """Return the report as readable lines, the reason first, then at most ``limit`` examples."""
205 lines = []
206 if self.catalogue_changed:
207 lines.append(
208 "the catalogue changed since the golden file was recorded; if that change is intended, "
209 "re-record with --update_golden and review the diff"
210 )
211 if self.spec_changed: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true
212 lines.append("the golden file was recorded over a different corpus spec")
213 if self.annotator_changed:
214 lines.append("note: checking a different annotator than the one that recorded the file")
215 if self.missing: 215 ↛ 216line 215 didn't jump to line 216 because the condition on line 215 was never true
216 lines.append(
217 f"{len(self.missing)} overlaps missing from the recording, e.g. {list(self.missing[:3])}"
218 )
219 if self.unexpected: 219 ↛ 220line 219 didn't jump to line 220 because the condition on line 219 was never true
220 lines.append(
221 f"{len(self.unexpected)} overlaps not in the golden file, e.g. {list(self.unexpected[:3])}"
222 )
223 if self.mismatches:
224 lines.append(f"{len(self.mismatches)} overlaps emit different terms:")
225 for key, golden_terms, recorded_terms in self.mismatches[:limit]:
226 lines.append(f" {key}: golden {list(golden_terms)} != recorded {list(recorded_terms)}")
227 if len(self.mismatches) > limit: 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 lines.append(f" ... and {len(self.mismatches) - limit} more")
229 if not lines:
230 lines.append("recorded terms match the golden file")
231 return lines