Coverage for src/python/ensembl/vep/bench/harness.py: 98%
93 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"""Measuring an annotator: the conformance gate that runs before any timing, and the timing itself.
16The gate comes first on purpose. A strategy that is fast because it is wrong is not a result, so a
17benchmark refuses to time anything until every candidate agrees with the reference on every
18overlap. The gate returns a report rather than exiting: the runner decides what a mismatch means for
19the process.
20"""
22from __future__ import annotations
24import time
25from collections.abc import Callable, Mapping, Sequence
27from attrs import field, frozen
29from ensembl.vep.annotators.base import Annotator
30from ensembl.vep.annotators.registry import available_annotators
31from ensembl.vep.models.overlap import OverlapConsequence, TranscriptVariationAllele
32from ensembl.vep.stats.profile import count_fact_computations
34__all__ = [
35 "KERNELS_STRATEGY",
36 "MISMATCH_LIMIT",
37 "REFERENCE_STRATEGY",
38 "GateReport",
39 "Timing",
40 "TimingPolicy",
41 "annotator_extras",
42 "conformance_gate",
43 "consequence_strategies",
44 "fact_cost",
45 "native_kernels_available",
46 "terms_of",
47 "time_best",
48]
50REFERENCE_STRATEGY = "consequence.linear"
51"""The strategy every other one must agree with."""
52KERNELS_STRATEGY = "consequence.columnar-kernels"
53"""The strategy that needs the compiled extension."""
54MISMATCH_LIMIT = 20
55"""Mismatches collected before the gate stops, so one broken strategy cannot flood the report."""
57_ANNOTATOR_COUNTERS = (
58 ("cache_hits", "candidate cache hits"),
59 ("cache_misses", "candidate cache misses"),
60 ("settled_early", "settled early"),
61 ("needed_expensive", "needed expensive tier"),
62 ("skipped_by_subsumption", "skipped by subsumption"),
63)
64_CACHE_COUNTERS = (
65 (
66 "zone_map_cache",
67 "zone map",
68 (
69 ("maps_built", "maps built"),
70 ("hit_count", "hits"),
71 ("eviction_count", "evictions"),
72 ("build_seconds", "build seconds"),
73 ("facts_served", "facts served"),
74 ),
75 ),
76 ("codon_cache", "codon cache", (("hit_count", "hits"), ("miss_count", "misses"))),
77 ("mapper_index_cache", "mapper cache", (("hit_count", "hits"), ("miss_count", "misses"))),
78)
81def terms_of(consequences: Sequence[OverlapConsequence]) -> list[str]:
82 """Return the terms of a consequence list, in order."""
83 return [consequence.term for consequence in consequences]
86def consequence_strategies() -> list[str]:
87 """Return every registered ``consequence.*`` strategy, the reference first."""
88 names = [name for name in available_annotators() if name.startswith("consequence.")]
89 if REFERENCE_STRATEGY in names: 89 ↛ 92line 89 didn't jump to line 92 because the condition on line 89 was always true
90 names.remove(REFERENCE_STRATEGY)
91 names.insert(0, REFERENCE_STRATEGY)
92 return names
95def native_kernels_available() -> bool:
96 """Return whether the strategy that needs the compiled extension is registered."""
97 return KERNELS_STRATEGY in available_annotators()
100@frozen(kw_only=True, auto_attribs=True)
101class GateReport:
102 """What the conformance gate found.
104 Attributes:
105 reference (str): The strategy the candidates were checked against.
106 candidates (tuple[str, ...]): The strategies checked.
107 overlaps (int): Overlaps checked.
108 mismatches (tuple[str, ...]): One line per disagreement found, at most ``MISMATCH_LIMIT``.
109 truncated (bool): Whether the gate stopped early at the limit.
110 """
112 reference: str
113 candidates: tuple[str, ...]
114 overlaps: int
115 mismatches: tuple[str, ...] = field(default=())
116 truncated: bool = field(default=False)
118 @property
119 def ok(self) -> bool:
120 """Return whether every candidate agreed on every overlap."""
121 return not self.mismatches
124def conformance_gate(
125 overlaps: Sequence[TranscriptVariationAllele],
126 *,
127 reference: Annotator[OverlapConsequence],
128 candidates: Mapping[str, Annotator[OverlapConsequence]],
129 reference_name: str = REFERENCE_STRATEGY,
130 limit: int = MISMATCH_LIMIT,
131) -> GateReport:
132 """Check every candidate against the reference, overlap by overlap.
134 Args:
135 overlaps (Sequence[TranscriptVariationAllele]): The overlaps to check.
136 reference (Annotator[OverlapConsequence]): The annotator whose terms are right by definition.
137 candidates (Mapping[str, Annotator[OverlapConsequence]]): Name -> annotator to check.
138 reference_name (str): The reference's name, for the report.
139 limit (int): Stop after this many mismatches.
141 Returns:
142 GateReport: What was found.
143 """
144 mismatches: list[str] = []
145 for overlap in overlaps:
146 expected = terms_of(reference.annotate_feature_overlap(overlap))
147 for name, candidate in candidates.items():
148 actual = terms_of(candidate.annotate_feature_overlap(overlap))
149 if actual == expected:
150 continue
151 mismatches.append(
152 f"{name} disagrees with {reference_name} on {overlap.feature.stable_id} at "
153 f"{overlap.overlapping_feature.start}: {actual} != {expected}"
154 )
155 if len(mismatches) >= limit:
156 return GateReport(
157 reference=reference_name,
158 candidates=tuple(candidates),
159 overlaps=len(overlaps),
160 mismatches=tuple(mismatches),
161 truncated=True,
162 )
163 return GateReport(
164 reference=reference_name,
165 candidates=tuple(candidates),
166 overlaps=len(overlaps),
167 mismatches=tuple(mismatches),
168 )
171@frozen(kw_only=True, auto_attribs=True)
172class TimingPolicy:
173 """How a measurement is taken.
175 Attributes:
176 repeats (int): Timed samples; the best is reported, as the least noisy.
177 warmup (int): Untimed passes first, so the timed ones do not include warming caches.
178 """
180 repeats: int = field(default=3)
181 warmup: int = field(default=1)
184@frozen(kw_only=True, auto_attribs=True)
185class Timing:
186 """The samples one measurement took.
188 Attributes:
189 samples (tuple[float, ...]): Elapsed seconds per timed pass.
190 warmup (int): Untimed passes that preceded them.
191 """
193 samples: tuple[float, ...]
194 warmup: int = field(default=0)
196 @property
197 def best(self) -> float:
198 """Return the fastest sample in seconds."""
199 return min(self.samples)
201 def ms_per_thousand(self, contexts: int) -> float:
202 """Return the best sample as milliseconds per thousand contexts."""
203 return self.best * 1_000_000 / max(1, contexts)
206def time_best(run_once: Callable[[], object], policy: TimingPolicy) -> Timing:
207 """Run a workload the policy's warmup times untimed, then time it the policy's repeats times."""
208 for _ in range(policy.warmup):
209 run_once()
210 samples = []
211 for _ in range(max(1, policy.repeats)):
212 started = time.perf_counter()
213 run_once()
214 samples.append(time.perf_counter() - started)
215 return Timing(samples=tuple(samples), warmup=policy.warmup)
218def fact_cost(
219 annotator: Annotator[OverlapConsequence], overlaps: Sequence[TranscriptVariationAllele]
220) -> tuple[float, float]:
221 """Return facts computed and declared cost charged, each per context, over one pass.
223 Instruments every fact process-wide for the pass; see ``stats.profile.count_fact_computations``.
224 """
225 contexts = max(1, len(overlaps))
226 with count_fact_computations() as counters:
227 for overlap in overlaps:
228 annotator.annotate_feature_overlap(overlap)
229 return counters["computed"] / contexts, counters["cost"] / contexts
232def annotator_extras(annotator: object) -> dict[str, object]:
233 """Return whatever instrumentation an annotator and its caches expose, labelled.
235 The counters live where the work is done: the staged strategies count on the annotator, while
236 the zone map, codon and mapper caches count on themselves, reached through the annotator's
237 context.
238 """
239 extras: dict[str, object] = {}
240 for attribute, label in _ANNOTATOR_COUNTERS:
241 if hasattr(annotator, attribute):
242 extras[label] = getattr(annotator, attribute)
243 context = getattr(annotator, "annotator_context", None)
244 if context is None:
245 return extras
246 for cache_attribute, prefix, counters in _CACHE_COUNTERS:
247 cache = getattr(context, cache_attribute, None)
248 if cache is None:
249 continue
250 for attribute, label in counters:
251 if hasattr(cache, attribute): 251 ↛ 250line 251 didn't jump to line 250 because the condition on line 251 was always true
252 extras[f"{prefix} {label}"] = getattr(cache, attribute)
253 return extras