Coverage for src/python/ensembl/vep/runner/bench/oracle.py: 77%
72 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"""Case-by-case comparison with the Perl ``VariationEffect.pm`` oracle."""
16from __future__ import annotations
18import logging
19import subprocess
20from typing import ClassVar
22from ensembl.vep.annotators.consequence.rules.rulesets import build_fact_ruleset
23from ensembl.vep.annotators.factory import build_annotator
24from ensembl.vep.bench.baseline import BenchResults
25from ensembl.vep.bench.harness import KERNELS_STRATEGY, REFERENCE_STRATEGY
26from ensembl.vep.bench.oracle import (
27 covered_cases,
28 covered_through_subsumption,
29 oracle_cases,
30 perl_seconds,
31 perl_terms,
32 perl_unavailable_reason,
33 python_seconds,
34 python_terms,
35)
36from ensembl.vep.config import Config
37from ensembl.vep.render.table import TableFormat, render_table
38from ensembl.vep.runner.base import ExitCode
39from ensembl.vep.runner.bench import common
40from ensembl.vep.runner.registry import register_runner
42__all__ = ["Runner"]
44logger = logging.getLogger(__name__)
46NO_TERMS = "(none)"
49@register_runner("bench.oracle")
50class Runner:
51 """Oracle benchmark runner for Python and Perl strategies.
53 A disagreement is reported, never gated on: the oracle is the external reference, and the Perl
54 script covers only four categories, so the question asked is whether our terms cover its terms.
56 Attributes:
57 name (ClassVar[str]): The registry name.
58 sections (ClassVar[tuple[str, ...]]): The configuration sections read.
59 description (ClassVar[str]): One-line description for the subcommand list.
60 """
62 name: ClassVar[str] = "bench.oracle"
63 sections: ClassVar[tuple[str, ...]] = ("logging", "bench", "bench_oracle")
64 description: ClassVar[str] = "compare our strategies with the Perl VariationEffect.pm oracle"
66 def __init__(self, config: Config) -> None:
67 """Hold the configuration."""
68 self.config = config
70 def run(self) -> ExitCode:
71 """Compare, time, report, and record."""
72 options = self.config.bench_oracle
73 try:
74 strategies = common.resolve_strategies(options.strategies, (REFERENCE_STRATEGY, KERNELS_STRATEGY))
75 table_format = TableFormat(common.table_format(self.config))
76 except ValueError as problem:
77 logger.error("%s", problem)
78 return ExitCode.USAGE
80 cases = oracle_cases()
81 annotators = {name: build_annotator(annotator=name) for name in strategies}
82 ours = {name: python_terms(annotator, cases) for name, annotator in annotators.items()}
84 reason = perl_unavailable_reason(options.perl_modules, options.perl_oracle_script)
85 perl: tuple[tuple[str, ...], ...] | None = None
86 if reason is not None: 86 ↛ 89line 86 didn't jump to line 89 because the condition on line 86 was always true
87 logger.warning("Perl oracle unavailable, comparing our strategies only: %s", reason)
88 else:
89 assert options.perl_modules is not None
90 try:
91 perl = perl_terms(options.perl_modules, options.perl_oracle_script, len(cases))
92 except (ValueError, OSError, subprocess.SubprocessError) as problem:
93 logger.error("the Perl oracle failed: %s", problem)
94 return ExitCode.FAILURE
96 headers = ("case", "perl (oracle)", *strategies)
97 rows = []
98 for index, case in enumerate(cases):
99 perl_cell = ",".join(perl[index]) or NO_TERMS if perl is not None else "unavailable"
100 rows.append(
101 (case.name, perl_cell, *(",".join(ours[name][index]) or NO_TERMS for name in strategies))
102 )
103 print(render_table(headers, rows, table_format))
104 if perl is not None: 104 ↛ 105line 104 didn't jump to line 105 because the condition on line 104 was never true
105 subsumes = {rule.term: rule.subsumes for rule in build_fact_ruleset().rules}
106 for name in strategies:
107 logger.info(
108 "%s covers the Perl-reported terms in %d/%d cases directly, "
109 "%d/%d counting the terms its emitted ones suppress by subsumption",
110 name,
111 covered_cases(perl, ours[name]),
112 len(cases),
113 covered_through_subsumption(perl, ours[name], subsumes),
114 len(cases),
115 )
117 timings = self._timings(annotators, cases, perl is not None)
118 print(
119 render_table(
120 ("subject", "ns/case (best)"),
121 [(subject, f"{value:.1f}") for subject, value in timings],
122 table_format,
123 )
124 )
125 results = BenchResults(
126 info=common.run_info(self.config, self.name),
127 rows=tuple(
128 {"corpus": "oracle", "configuration": subject, "ns_per_case": value}
129 for subject, value in timings
130 ),
131 )
132 return common.record_results(self.config, results)
134 def _timings(self, annotators: dict, cases: tuple, with_perl: bool) -> list[tuple[str, float]]:
135 """Return best nanoseconds per case for each strategy and, when available, for Perl."""
136 options = self.config.bench_oracle
137 repeats = self.config.bench.repeats
138 number = options.oracle_number
139 per_case = number * len(cases)
140 timings = []
141 for name, annotator in annotators.items():
142 best = min(python_seconds(annotator, cases, number=number, repeats=repeats))
143 timings.append((f"python {name}", best / per_case * 1e9))
144 if with_perl and options.perl_modules is not None: 144 ↛ 145line 144 didn't jump to line 145 because the condition on line 144 was never true
145 best = min(
146 perl_seconds(options.perl_modules, options.perl_oracle_script, number=number, repeats=repeats)
147 )
148 timings.append(("perl (includes interpreter start-up)", best / per_case * 1e9))
149 return timings