Coverage for src/python/ensembl/vep/annotators/consequence/strategies/columnar.py: 100%
182 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"""Evaluate consequence rules bit-parallel across an overlap batch.
16Each fact is represented by a Python integer whose bit ``i`` contains the value for overlap ``i``.
17Rule formulas become bitwise operations, paying Python dispatch once per rule and batch rather than
18once per rule and overlap.
20Evaluation orders conjuncts by closure cost and carries a live mask of unresolved overlaps. A fact
21column is materialised only for that mask, while each plan node guarantees correct bits within its
22input mask and zero elsewhere. Because child masks and results only shrink, unpopulated bits cannot
23affect a decided result.
24"""
26from __future__ import annotations
28from collections.abc import Sequence
29import logging
30from typing import TYPE_CHECKING, ClassVar
32from attrs import frozen
34from ensembl.vep.annotators.consequence.strategies.base import ConsequenceAnnotator
35from ensembl.vep.annotators.consequence.facts.base import REGISTRY, get_fact, total_cost
36from ensembl.vep.annotators.consequence.context.annotator import AnnotatorContext
37from ensembl.vep.annotators.consequence.context.fact import FactContext
38from ensembl.vep.annotators.registry import register_annotator
39from ensembl.vep.annotators.consequence.rules.expressions import And, Atom, Expr, Not, Or
40from ensembl.vep.annotators.consequence.rules.rulesets import (
41 FactRuleSet,
42 build_fact_ruleset,
43 prune,
44)
45from ensembl.vep.trace import AnnotationTrace, TraceRecorder, describe_overlap
46from ensembl.vep.trace import reconstruct
47from ensembl.vep.models.overlap import FeatureOverlap, OverlapConsequence, TranscriptVariationAllele
49if TYPE_CHECKING:
50 from ensembl.vep.caches.codon_cache import CodonCache
51 from ensembl.vep.caches.zone_map import ZoneMapCache
53__all__ = [
54 "BitColumnBuffer",
55 "ColumnarFactsAnnotator",
56 "DEFAULT_BATCH_SIZE",
57 "PlanNode",
58 "RulePlan",
59 "RulePlanSet",
60]
62logger = logging.getLogger(__name__)
64DEFAULT_BATCH_SIZE = 256
65"""Default maximum number of overlaps evaluated together as one bit-parallel batch. Increase to amortise the
66plan-walking overhead over more overlaps, decrease to reduce peak memory usage. It has been observed that
67increasing does not always improve speed, because of big-int arithmetic overhead."""
70class BitColumnBuffer:
71 """Materialise fact bit-columns lazily for one overlap batch."""
73 def __init__(self, fact_contexts: Sequence[FactContext]) -> None:
74 """Initialize the buffer.
76 Args:
77 fact_contexts (Sequence[FactContext]): The overlaps' fact contexts, batch-index order.
78 """
79 self._fact_contexts = fact_contexts
80 self._known_bits: dict[str, int] = {}
81 self._value_bits: dict[str, int] = {}
83 def seed(self, fact_name: str, column: int, known_mask: int) -> None:
84 """Mark a fact's column as already computed for every context in ``known_mask``.
86 For a caller that produced the whole column by cheaper means than calling ``get_fact``
87 per context. Unlike FactContext.prefill this does not touch the per-overlap memo, so a fact
88 seeded here is visible to the rule loop but not to a ``get_fact`` call inside another fact's
89 body. Therefore only seed leaf facts nothing else reads, or prefill the memo as well.
91 Args:
92 fact_name (str): The fact atom being seeded.
93 column (int): Bit ``i`` set where the fact is true for context ``i``.
94 known_mask (int): The contexts this column is exact for.
95 """
96 self._value_bits[fact_name] = column & known_mask
97 self._known_bits[fact_name] = self._known_bits.get(fact_name, 0) | known_mask
99 def column(self, fact_name: str, live_mask: int) -> int:
100 """Return the bit-column for ``fact_name`` within ``live_mask``.
102 Args:
103 fact_name (str): The fact atom to materialise a column for.
104 live_mask (int): The set of overlap indices (as bits) the caller needs an answer for.
106 Returns:
107 int: Bits set for every overlap index in ``live_mask`` where the fact is true. Bits
108 outside ``live_mask`` are not guaranteed to mean anything.
109 """
110 missing_mask = live_mask & ~self._known_bits.get(fact_name, 0)
111 if missing_mask:
112 value_bits = self._value_bits.get(fact_name, 0)
113 remaining_mask = missing_mask
114 while remaining_mask:
115 lowest_bit = remaining_mask & -remaining_mask
116 context_index = lowest_bit.bit_length() - 1
117 if get_fact(self._fact_contexts[context_index], fact_name):
118 value_bits |= lowest_bit
119 remaining_mask ^= lowest_bit
120 self._value_bits[fact_name] = value_bits
121 self._known_bits[fact_name] = self._known_bits.get(fact_name, 0) | missing_mask
122 return self._value_bits.get(fact_name, 0)
125@frozen(kw_only=True, auto_attribs=True)
126class _AtomPlanNode:
127 """A compiled plan node for a single fact atom."""
129 fact_name: str
131 def evaluate(self, live_mask: int, bit_columns: BitColumnBuffer) -> int:
132 """Evaluate this atom over ``live_mask``.
134 Args:
135 live_mask (int): The overlap indices (as bits) still undecided for this subtree.
136 bit_columns (BitColumnBuffer): The batch's lazily-materialised fact columns.
138 Returns:
139 int: Bits set where the fact is true, within ``live_mask``.
140 """
141 return bit_columns.column(self.fact_name, live_mask) & live_mask
144@frozen(kw_only=True, auto_attribs=True)
145class _NotPlanNode:
146 """A compiled plan node for a negation."""
148 child: PlanNode
150 def evaluate(self, live_mask: int, bit_columns: BitColumnBuffer) -> int:
151 """Evaluate this negation over ``live_mask``.
153 Args:
154 live_mask (int): The overlap indices (as bits) still undecided for this subtree.
155 bit_columns (BitColumnBuffer): The batch's lazily-materialised fact columns.
157 Returns:
158 int: Bits set where the child is false, within ``live_mask``.
159 """
160 return live_mask & ~self.child.evaluate(live_mask, bit_columns)
163@frozen(kw_only=True, auto_attribs=True)
164class _AndPlanNode:
165 """A compiled plan node for a conjunction, children ordered cheapest-first."""
167 children: tuple[PlanNode, ...]
169 def evaluate(self, live_mask: int, bit_columns: BitColumnBuffer) -> int:
170 """Evaluate this conjunction, narrowing the mask as each child settles.
172 Args:
173 live_mask (int): The overlap indices (as bits) still undecided for this subtree.
174 bit_columns (BitColumnBuffer): The batch's lazily-materialised fact columns.
176 Returns:
177 int: Bits set where every child is true, within ``live_mask``.
178 """
179 still_live = live_mask
180 for child in self.children:
181 if not still_live:
182 break
183 still_live &= child.evaluate(still_live, bit_columns)
184 return still_live
187@frozen(kw_only=True, auto_attribs=True)
188class _OrPlanNode:
189 """A compiled plan node for a disjunction, children ordered cheapest-first."""
191 children: tuple[PlanNode, ...]
193 def evaluate(self, live_mask: int, bit_columns: BitColumnBuffer) -> int:
194 """Evaluate this disjunction over ``live_mask``.
196 Tracks what is still *undecided* (neither proven True nor exhausted), the dual of the
197 And case, so each child is only asked about the indices no earlier child has settled.
199 Args:
200 live_mask (int): The overlap indices (as bits) still undecided for this subtree.
201 bit_columns (BitColumnBuffer): The batch's lazily-materialised fact columns.
203 Returns:
204 int: Bits set where any child is true, within ``live_mask``.
205 """
206 undecided_mask = live_mask
207 for child in self.children:
208 if not undecided_mask:
209 break
210 undecided_mask &= ~child.evaluate(undecided_mask, bit_columns)
211 return live_mask & ~undecided_mask
214PlanNode = _AtomPlanNode | _NotPlanNode | _AndPlanNode | _OrPlanNode
217@frozen(kw_only=True, auto_attribs=True)
218class RulePlan:
219 """Represent a rule as a cost-ordered bit-parallel evaluation plan.
221 Attributes:
222 root_plan_node (PlanNode): The root of the compiled plan.
223 """
225 root_plan_node: PlanNode
226 _transitive_closure_cache: ClassVar[dict[str, frozenset[str]]] = {}
227 """Shared across every RulePlan, deliberately, since the fact dependency graph is a property of
228 REGISTRY, not of any one rule. A per-instance cache would rebuild the same closures once per rule.
229 """
231 @classmethod
232 def build(cls, expression: Expr) -> RulePlan:
233 """Compile a rule's Expr formula into a RulePlan.
235 Args:
236 expression (Expr): The formula to compile.
238 Returns:
239 RulePlan: The compiled plan, with every ``And``/``Or`` node's children sorted by
240 ascending cost so the cheapest conjunct/disjunct gets the chance to settle the
241 whole subtree first.
242 """
243 return cls(root_plan_node=cls._compile(expression))
245 def evaluate(self, live_mask: int, bit_columns: BitColumnBuffer) -> int:
246 """Evaluate this plan over a live mask, short-circuiting as children settle.
248 Args:
249 live_mask (int): The set of overlap indices (as bits) still undecided.
250 bit_columns (BitColumnBuffer): The batch's lazily-materialised fact columns.
252 Returns:
253 int: Bits set for every overlap index in ``live_mask`` where the rule evaluates True.
254 """
255 return self.root_plan_node.evaluate(live_mask, bit_columns)
257 @classmethod
258 def _compile(cls, expression: Expr) -> PlanNode:
259 """Recursively compile ``expression`` into cost-ordered plan nodes.
261 Args:
262 expression (Expr): The (sub)expression to compile.
264 Returns:
265 PlanNode: The compiled node.
267 Raises:
268 TypeError: If ``expression`` is a node type this annotator does not support.
269 """
270 if isinstance(expression, Atom):
271 return _AtomPlanNode(fact_name=expression.name)
272 if isinstance(expression, Not):
273 return _NotPlanNode(child=cls._compile(expression.child))
274 if isinstance(expression, (And, Or)):
275 ordered_children = sorted(expression.children, key=cls._expression_cost)
276 compiled_children = tuple(cls._compile(child) for child in ordered_children)
277 return (
278 _AndPlanNode(children=compiled_children)
279 if isinstance(expression, And)
280 else _OrPlanNode(children=compiled_children)
281 )
282 raise TypeError(f"unsupported expression node type: {type(expression).__name__}")
284 @classmethod
285 def _expression_cost(cls, expression: Expr) -> int:
286 """Returns the cost of deciding ``expression``, counting each shared fact dependency once.
288 Args:
289 expression (Expr): The expression (typically one conjunct/disjunct of a rule's
290 formula) to cost.
292 Returns:
293 int: The total cost of every fact ``expression`` transitively depends on.
294 """
295 reachable_fact_names: set[str] = set()
296 for atom_name in expression.atoms():
297 reachable_fact_names |= cls._transitive_closure(atom_name)
298 return total_cost(reachable_fact_names)
300 @classmethod
301 def _transitive_closure(cls, fact_name: str) -> frozenset[str]:
302 """Returns ``fact_name`` plus every fact its declared ``deps`` will pull in, transitively.
304 Args:
305 fact_name (str): The fact to start from.
307 Returns:
308 frozenset[str]: ``fact_name`` and every fact reachable from it via ``deps``.
309 """
310 cache = cls._transitive_closure_cache
311 cached = cache.get(fact_name)
312 if cached is not None:
313 return cached
314 cache[fact_name] = frozenset({fact_name}) # break any cycle in the declarations
315 reachable = {fact_name}
316 for dependency_name in REGISTRY[fact_name].deps:
317 reachable |= cls._transitive_closure(dependency_name)
318 result = frozenset(reachable)
319 cache[fact_name] = result
320 return result
323@frozen(kw_only=True, auto_attribs=True)
324class RulePlanSet:
325 """Pair a rule set with one compiled plan per rule.
327 Attributes:
328 ruleset (FactRuleSet): The compiled rule set, in rank order.
329 plans (tuple[RulePlan, ...]): One compiled plan per rule in ``ruleset.rules``, same order.
330 """
332 ruleset: FactRuleSet
333 plans: tuple[RulePlan, ...]
335 @classmethod
336 def build(cls, ruleset: FactRuleSet) -> RulePlanSet:
337 """Compile one plan per rule in ``ruleset``.
339 Args:
340 ruleset (FactRuleSet): The rule set to compile plans for.
342 Returns:
343 RulePlanSet: The rule set paired with its compiled plans.
344 """
345 return cls(ruleset=ruleset, plans=tuple(RulePlan.build(rule.when) for rule in ruleset.rules))
347 def hit_terms_by_context(self, bit_columns: BitColumnBuffer, context_count: int) -> list[list[str]]:
348 """Return the terms that evaluated as true for each fact context.
350 Args:
351 bit_columns (BitColumnBuffer): The batch's fact columns.
352 context_count (int): Number of overlaps in this chunk.
354 Returns:
355 list[list[str]]: The terms that fired for each fact context, in rule rank order.
356 """
357 hit_terms_by_context: list[list[str]] = [[] for _ in range(context_count)]
358 full_mask = (1 << context_count) - 1
359 for rule, plan in zip(self.ruleset.rules, self.plans):
360 fired_mask = plan.evaluate(full_mask, bit_columns) & full_mask
361 remaining_mask = fired_mask
362 while remaining_mask:
363 lowest_bit = remaining_mask & -remaining_mask
364 context_index = lowest_bit.bit_length() - 1
365 hit_terms_by_context[context_index].append(rule.term)
366 remaining_mask ^= lowest_bit
367 return hit_terms_by_context
369 def evaluate_over_columns(
370 self, bit_columns: BitColumnBuffer, context_count: int
371 ) -> list[list[OverlapConsequence]]:
372 """Evaluate every rule bit-parallel over a column buffer according to their plan.
374 The column buffer here, already built, gets populated via plain lazy materialisation.
376 Args:
377 bit_columns (BitColumnBuffer): The batch's fact columns.
378 context_count (int): Number of overlaps in this chunk.
380 Returns:
381 list[list[OverlapConsequence]]: One consequence list per input context, same order.
382 """
383 ruleset = self.ruleset
384 return [
385 [
386 ruleset.by_term[term].to_overlap_consequence()
387 for term in prune(ruleset, hit_terms, apply_default=False)
388 ]
389 for hit_terms in self.hit_terms_by_context(bit_columns, context_count)
390 ]
393@register_annotator("consequence.columnar")
394class ColumnarFactsAnnotator(ConsequenceAnnotator[FactRuleSet]):
395 """Evaluate consequence rules bit-parallel over overlap batches.
397 Attributes:
398 name (str): Registry name, "consequence.columnar".
399 ruleset (FactRuleSet): The compiled rule set this annotator evaluates.
400 batch_size (int): Maximum number of overlaps evaluated together as one bit-parallel batch.
401 last_traces (list[AnnotationTrace]): One derivation per overlap in the most recent
402 annotate_feature_overlaps call, in the same order, or an empty list if that call did
403 not trace. The inherited last_trace attribute mirrors this list's final entry.
404 """
406 name = "consequence.columnar"
408 def __init__(
409 self,
410 ruleset: FactRuleSet | None = None,
411 batch_size: int = DEFAULT_BATCH_SIZE,
412 annotator_context: AnnotatorContext | None = None,
413 *,
414 zone_map: ZoneMapCache | None = None,
415 codon_cache: CodonCache | None = None,
416 ) -> None:
417 """Initialize the annotator.
419 Args:
420 ruleset (FactRuleSet | None): The rule set to evaluate, or None to build the default
421 rule set from the checked-in consequence catalogue.
422 batch_size (int): Maximum number of overlaps evaluated together as one batch.
423 annotator_context (AnnotatorContext | None): Run-scoped caches to evaluate against,
424 or None (the default) for a fresh, private one.
425 zone_map (ZoneMapCache | None): Optional zone-map cache.
426 codon_cache (CodonCache | None): Optional shared-codon cache.
427 """
428 super().__init__(
429 ruleset if ruleset is not None else build_fact_ruleset(),
430 annotator_context,
431 zone_map=zone_map,
432 codon_cache=codon_cache,
433 )
434 self.batch_size = batch_size
435 self._planset = RulePlanSet.build(self.ruleset)
436 self.last_traces: list[AnnotationTrace] = []
438 def _evaluate_chunk(self, fact_contexts: Sequence[FactContext]) -> list[list[OverlapConsequence]]:
439 """Evaluate every rule, bit-parallel, over one chunk of at most ``batch_size`` overlaps.
441 Args:
442 fact_contexts (Sequence[FactContext]): The chunk's fact contexts, batch-index order.
444 Returns:
445 list[list[OverlapConsequence]]: One consequence list per input context, same order.
446 """
447 context_count = len(fact_contexts)
448 if context_count == 0:
449 return []
450 bit_columns = BitColumnBuffer(fact_contexts)
451 return self._planset.evaluate_over_columns(bit_columns, context_count)
453 def _trace_chunk(self, fact_contexts: Sequence[FactContext]) -> list[AnnotationTrace]:
454 """Debug-only replay of one already-evaluated chunk, to explain each overlap.
456 Deliberately a second and independent pass over the plan rather than a change to _evaluate_chunk which
457 is the hot batch path. Only ever called when tracing is already known to be enabled.
459 Args:
460 fact_contexts (Sequence[FactContext]): The already-evaluated chunk, in the same order
461 passed to the preceding ``_evaluate_chunk`` call.
463 Returns:
464 list[AnnotationTrace]: One derivation per context, in the same order.
465 """
466 context_count = len(fact_contexts)
467 if context_count == 0:
468 return []
469 # Taken before the replay: every column below is a memo hit, and get_fact counts those,
470 # so read counts gathered afterwards would include reads the real pass never made.
471 fact_events_by_context = [reconstruct.memo_fact_events(context) for context in fact_contexts]
473 bit_columns = BitColumnBuffer(fact_contexts)
474 hit_terms_by_context = self._planset.hit_terms_by_context(bit_columns, context_count)
476 traces = []
477 for context_index, fact_context in enumerate(fact_contexts):
478 hit_terms = hit_terms_by_context[context_index]
479 trace = AnnotationTrace(
480 fact_events=fact_events_by_context[context_index],
481 rule_events=reconstruct.plain_rule_events(self.ruleset.rules, hit_terms),
482 prune_events=reconstruct.subsumption_events(self.ruleset.by_term, hit_terms),
483 emitted_terms=tuple(prune(self.ruleset, hit_terms, apply_default=False)),
484 annotator_name=self.name,
485 overlap_label=describe_overlap(fact_context.overlap),
486 )
487 traces.append(trace)
488 logger.debug(trace.format_explanation())
489 return traces
491 def annotate_feature_overlaps(self, overlaps: Sequence[FeatureOverlap]) -> list[list[OverlapConsequence]]:
492 """Calculate consequences for a batch of overlaps at once.
494 Args:
495 overlaps (Sequence[FeatureOverlap]): The overlaps to annotate, in order.
497 Returns:
498 list[list[OverlapConsequence]]: One consequence list per input overlap, same order.
500 Raises:
501 TypeError: If any element of ``overlaps`` is not a TranscriptVariationAllele.
502 """
503 transcript_variation_alleles: list[TranscriptVariationAllele] = []
504 for overlap in overlaps:
505 if not isinstance(overlap, TranscriptVariationAllele):
506 raise TypeError(
507 f"{type(self).__name__} only annotates TranscriptVariationAllele overlaps, got "
508 f"{type(overlap).__name__}"
509 )
510 transcript_variation_alleles.append(overlap)
512 debug_enabled = logger.isEnabledFor(logging.DEBUG)
513 fact_contexts = [
514 FactContext(
515 overlap=overlap,
516 recorder=(TraceRecorder() if debug_enabled else None),
517 annotator_context=self.annotator_context,
518 )
519 for overlap in transcript_variation_alleles
520 ]
521 results: list[list[OverlapConsequence]] = []
522 traces: list[AnnotationTrace] = []
523 for chunk_start in range(0, len(fact_contexts), self.batch_size):
524 chunk = fact_contexts[chunk_start : chunk_start + self.batch_size]
525 # Caches are applied per overlap, before the chunk's columns are materialised, because
526 # prefilling after expensive tier gets called would save nothing.
527 for fact_context in chunk:
528 self.annotator_context.prepare(fact_context)
529 results.extend(self._evaluate_chunk(chunk))
530 if debug_enabled:
531 traces.extend(self._trace_chunk(chunk))
533 self.last_traces = traces
534 self.last_trace = traces[-1] if traces else None
535 return results