Coverage for src/python/ensembl/vep/bench/oracle.py: 83%
97 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"""The Perl oracle: the same cases through our annotators and through ``VariationEffect.pm``.
16The oracle is the external reference -- the whole point is that it is *not* us -- so a
17disagreement is reported, never gated on. The Perl script tests only the coding, intronic, upstream
18and downstream categories, so the comparison asks whether our terms *cover* the Perl ones, not
19whether they are equal.
21Coverage is counted twice, because the direct count undercounts agreement. The Perl script reports
22raw predicates, while our annotators emit terms after subsumption: an intronic variant in the
23polypyrimidine tract emits ``splice_polypyrimidine_tract_variant``, which suppresses the
24``intron_variant`` the Perl side reports. Counting the terms our emitted ones suppress, through the
25catalogue's ``subsumes`` chains, separates that from a real disagreement.
27The case list here and ``build_cases`` in ``bench/variation_effect.pl`` must stay aligned by name
28and order; ``CASE_NAMES`` is what a test pins against the Perl file. The transcript is built with
29the corpus's own ``build_transcript``, so its translation is derived exactly as the suite's is --
30the hand-rolled builder this replaces had fallen out of step with the model and no longer ran.
31"""
33from __future__ import annotations
35import json
36import shutil
37import subprocess
38import time
39from collections.abc import Mapping, Sequence
40from pathlib import Path
42from attrs import frozen
44from ensembl.vep.annotators.base import Annotator
45from ensembl.vep.common import CoordSystemLevel, Strand
46from ensembl.vep.corpus.synthetic.components.transcript import build_transcript
47from ensembl.vep.models.genic import Transcript
48from ensembl.vep.models.overlap import OverlapConsequence, TranscriptVariationAllele
49from ensembl.vep.models.sequence import CoordSystem, Slice
50from ensembl.vep.models.variation import VariationAllele
52__all__ = [
53 "CASE_NAMES",
54 "OracleCase",
55 "covered_cases",
56 "covered_through_subsumption",
57 "oracle_cases",
58 "oracle_transcript",
59 "perl_seconds",
60 "perl_terms",
61 "perl_unavailable_reason",
62 "python_seconds",
63 "python_terms",
64 "subsumption_closure",
65]
67CASE_NAMES = (
68 "coding_exact",
69 "coding_near_boundary",
70 "intron_primary",
71 "intron_secondary",
72 "upstream_near",
73 "upstream_far",
74 "downstream_near",
75 "downstream_far",
76 "no_hit",
77)
78"""The cases, in the order the Perl script builds and reports them."""
80_CHROMOSOME_LENGTH = 10000
81_PERL_TIMEOUT_SECONDS = 600
84@frozen(kw_only=True, auto_attribs=True)
85class OracleCase:
86 """A named overlap, paired with the Perl case of the same name.
88 Attributes:
89 name (str): The case name, shared with the Perl script.
90 overlap (TranscriptVariationAllele): The overlap to annotate.
91 """
93 name: str
94 overlap: TranscriptVariationAllele
97def oracle_transcript() -> Transcript:
98 """Return a small forward-strand coding transcript: two exons around one intron, all of both coding.
100 Exon 1 is 1000-1029 and exon 2 1050-1088, so the CDS is 69 bases -- 23 codons, a multiple of
101 three, so no partial-codon edge leaks into a case that is not about one. The background is a
102 plain ``A`` repeat: the comparison needs only the category a variant lands in to be
103 unambiguous, not a realistic open reading frame.
104 """
105 chromosome = Slice(
106 coord_system=CoordSystem(name="chromosome", level=CoordSystemLevel.CHROMOSOME),
107 seq_region_name="1",
108 start=1,
109 end=_CHROMOSOME_LENGTH,
110 strand=Strand.FORWARD,
111 )
112 with chromosome.unsafe() as unsafe_slice:
113 setattr(unsafe_slice, "_seq", "A" * _CHROMOSOME_LENGTH)
114 return build_transcript(
115 stable_id="ENST00000000001",
116 synthetic_slice=chromosome,
117 strand=Strand.FORWARD,
118 exons_genomic_ascending=[(1000, 1029), (1050, 1088)],
119 cds_genomic_bounds=(1000, 1088),
120 gene=None,
121 biotype="protein_coding",
122 )
125def _snv(transcript: Transcript, position: int) -> TranscriptVariationAllele:
126 """Return an A>T SNV at a genomic position, against the transcript."""
127 allele = VariationAllele(
128 start=position,
129 end=position,
130 strand=Strand.FORWARD,
131 slice=transcript.slice,
132 reference_allele="A",
133 alternate_allele="T",
134 )
135 return TranscriptVariationAllele(feature=transcript, overlapping_feature=allele)
138def oracle_cases() -> tuple[OracleCase, ...]:
139 """Return the cases, named and ordered as the Perl script's."""
140 transcript = oracle_transcript()
141 positions = (
142 1010, # mid exon 1, well inside the CDS
143 1028, # two bases from the donor site
144 1039, # deep intronic, the intron's midpoint
145 1032, # near the donor site, offset +3
146 transcript.start - 1,
147 transcript.start - 4000,
148 transcript.end + 1,
149 transcript.end + 4000,
150 transcript.end + 6000, # beyond the 5 kb flank window
151 )
152 return tuple(
153 OracleCase(name=name, overlap=_snv(transcript, position))
154 for name, position in zip(CASE_NAMES, positions, strict=True)
155 )
158def python_terms(
159 annotator: Annotator[OverlapConsequence], cases: Sequence[OracleCase]
160) -> tuple[tuple[str, ...], ...]:
161 """Return one annotator's terms for every case, in case order."""
162 return tuple(
163 tuple(consequence.term for consequence in annotator.annotate_feature_overlap(case.overlap))
164 for case in cases
165 )
168def perl_unavailable_reason(perl_modules: Path | None, script: Path) -> str | None:
169 """Return why the Perl oracle cannot run here, or None if it can."""
170 if shutil.which("perl") is None: 170 ↛ 171line 170 didn't jump to line 171 because the condition on line 170 was never true
171 return "perl is not on PATH"
172 if not script.is_file():
173 return f"oracle script not found: {script}"
174 if perl_modules is None:
175 return "no ensembl-variation modules directory given (--perl_modules)"
176 if not perl_modules.is_dir(): 176 ↛ 178line 176 didn't jump to line 178 because the condition on line 176 was always true
177 return f"ensembl-variation modules not found at {perl_modules}"
178 return None
181def _perl_command(perl_modules: Path, script: Path, *arguments: str) -> list[str]:
182 """Return the command line that runs the oracle script."""
183 return ["perl", "-I", str(perl_modules), str(script), *arguments]
186def perl_terms(perl_modules: Path, script: Path, case_count: int) -> tuple[tuple[str, ...], ...]:
187 """Run the oracle for its terms, one tuple per case in its own order.
189 Raises:
190 ValueError: If the oracle reports a different number of cases, meaning the two case lists
191 have drifted apart.
192 subprocess.CalledProcessError: If the script fails.
193 """
194 result = subprocess.run(
195 _perl_command(perl_modules, script, "--mode", "json"),
196 check=True,
197 capture_output=True,
198 text=True,
199 timeout=_PERL_TIMEOUT_SECONDS,
200 )
201 parsed = json.loads(result.stdout)
202 if len(parsed) != case_count:
203 raise ValueError(
204 f"the Perl oracle reported {len(parsed)} cases and this side has {case_count}: "
205 "build_cases in the Perl script and CASE_NAMES here have drifted apart"
206 )
207 return tuple(tuple(terms) for terms in parsed)
210def perl_seconds(perl_modules: Path, script: Path, *, number: int, repeats: int) -> list[float]:
211 """Return the elapsed seconds of each timed oracle run of ``number`` workload executions.
213 Each run is a whole process, so the figure includes Perl's start-up; the per-case number it
214 yields is an upper bound, and says so wherever it is reported.
215 """
216 durations = []
217 for _ in range(max(1, repeats)):
218 started = time.perf_counter()
219 subprocess.run(
220 _perl_command(perl_modules, script, "--mode", "bench", "--number", str(number)),
221 check=True,
222 capture_output=True,
223 timeout=_PERL_TIMEOUT_SECONDS,
224 )
225 durations.append(time.perf_counter() - started)
226 return durations
229def python_seconds(
230 annotator: Annotator[OverlapConsequence], cases: Sequence[OracleCase], *, number: int, repeats: int
231) -> list[float]:
232 """Return the elapsed seconds of each timed run of ``number`` workload executions."""
233 durations = []
234 for _ in range(max(1, repeats)):
235 started = time.perf_counter()
236 for _ in range(number):
237 for case in cases:
238 annotator.annotate_feature_overlap(case.overlap)
239 durations.append(time.perf_counter() - started)
240 return durations
243def covered_cases(perl: Sequence[Sequence[str]], ours: Sequence[Sequence[str]]) -> int:
244 """Return how many cases our terms cover every Perl-reported term of."""
245 return sum(1 for perl_case, our_case in zip(perl, ours, strict=True) if set(perl_case) <= set(our_case))
248def subsumption_closure(subsumes: Mapping[str, Sequence[str]]) -> dict[str, frozenset[str]]:
249 """Return every term each term suppresses, directly or through a chain of ``subsumes``."""
250 closure: dict[str, frozenset[str]] = {}
251 for term in subsumes:
252 reached: set[str] = set()
253 pending = list(subsumes.get(term, ()))
254 while pending:
255 current = pending.pop()
256 if current in reached: 256 ↛ 257line 256 didn't jump to line 257 because the condition on line 256 was never true
257 continue
258 reached.add(current)
259 pending.extend(subsumes.get(current, ()))
260 closure[term] = frozenset(reached)
261 return closure
264def covered_through_subsumption(
265 perl: Sequence[Sequence[str]], ours: Sequence[Sequence[str]], subsumes: Mapping[str, Sequence[str]]
266) -> int:
267 """Return how many cases our terms cover, counting the terms they suppress as covered.
269 Args:
270 perl (Sequence[Sequence[str]]): The Perl-reported terms, per case.
271 ours (Sequence[Sequence[str]]): Our emitted terms, per case.
272 subsumes (Mapping[str, Sequence[str]]): Term -> the terms it directly suppresses.
274 Returns:
275 int: Cases whose every Perl-reported term is emitted by us or suppressed by a term we emit.
276 """
277 closure = subsumption_closure(subsumes)
278 covered = 0
279 for perl_case, our_case in zip(perl, ours, strict=True):
280 explained = set(our_case)
281 for term in our_case:
282 explained |= closure.get(term, frozenset())
283 if set(perl_case) <= explained:
284 covered += 1
285 return covered