Coverage for src/python/ensembl/vep/annotators/consequence/strategies/columnar_kernels.py: 99%
67 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"""Columnar-staged evaluation whose cheapest fact columns are filled by native batch kernels.
16Only flat integer arrays cross the native boundary; model objects remain in Python. Kernels process
17whole columns because a scalar boundary crossing costs more than the operations being accelerated.
19The seeded facts cover short-variant shape and feature-span comparisons that remain per-context
20work after zone-map prefill. Exon and intron kernels are not seeded here because building their CSR
21arrays costs more than the Python scan when a zone map has not already supplied the values.
22"""
24from __future__ import annotations
26from collections.abc import Sequence
27import logging
28from typing import TYPE_CHECKING
30from ensembl.vep.annotators.registry import register_annotator
31from ensembl.vep.annotators.consequence.strategies.columnar import DEFAULT_BATCH_SIZE
32from ensembl.vep.annotators.consequence.strategies.columnar_staged import ColumnarStagedAnnotator
33from ensembl.vep.annotators.consequence.context.annotator import AnnotatorContext
34from ensembl.vep.annotators.consequence.context.fact import FactContext
35from ensembl.vep.annotators.consequence.rules.rulesets import FactRuleSet
36from ensembl.vep.common.constants import EMPTY_ALLELE
37from ensembl.vep.models.variation import StructuralVariationAllele
38from ensembl.vep.ensembl_vep_core import ( # pylint: disable=no-name-in-module
39 batch_contain_span,
40 batch_overlap_span,
41 batch_variant_shapes,
42)
44if TYPE_CHECKING:
45 from ensembl.vep.caches.codon_cache import CodonCache
46 from ensembl.vep.caches.zone_map import ZoneMapCache
48__all__ = ["ColumnarKernelsAnnotator", "SEEDED_FACT_NAMES"]
50logger = logging.getLogger(__name__)
52# The short-variant shape facts, paired with the index of the kernel mask that answers each.
53_SHORT_SHAPE_FACTS: tuple[tuple[str, int], ...] = (
54 ("is_snv", 0),
55 ("is_short_insertion", 1),
56 ("is_short_deletion", 2),
57)
59SEEDED_FACT_NAMES: tuple[str, ...] = tuple(name for name, _ in _SHORT_SHAPE_FACTS) + (
60 "is_short",
61 "overlap_feature",
62 "contain_feature",
63)
64"""Facts filled by native kernels and checked against their Python implementations in tests."""
67@register_annotator("consequence.columnar-kernels")
68class ColumnarKernelsAnnotator(ColumnarStagedAnnotator):
69 """Evaluate staged columns with native kernels for inexpensive facts.
71 Identical output to ColumnarStagedAnnotator by construction: the kernels compute the same
72 formulas, and everything they do not seed falls through to the ordinary Python path.
74 Attributes:
75 name (str): Registry name, "consequence.columnar-kernels".
76 kernel_calls (int): Number of FFI crossings made so far.
77 columns_seeded (int): Number of (fact, overlap) values filled by a kernel so far.
78 """
80 name = "consequence.columnar-kernels"
82 def __init__(
83 self,
84 ruleset: FactRuleSet | None = None,
85 batch_size: int = DEFAULT_BATCH_SIZE,
86 annotator_context: AnnotatorContext | None = None,
87 *,
88 zone_map: ZoneMapCache | None = None,
89 codon_cache: CodonCache | None = None,
90 ) -> None:
91 """Initialize the annotator.
93 Args:
94 ruleset (FactRuleSet | None): The rule set to evaluate, or None for the default.
95 batch_size (int): Maximum number of overlaps evaluated together as one batch.
96 annotator_context (AnnotatorContext | None): Run-scoped caches to evaluate against,
97 or None (the default) for a fresh, private one.
98 zone_map (ZoneMapCache | None): Optional zone-map cache.
99 codon_cache (CodonCache | None): Optional shared-codon cache.
100 """
101 super().__init__(
102 ruleset,
103 batch_size,
104 annotator_context,
105 zone_map=zone_map,
106 codon_cache=codon_cache,
107 )
108 self.kernel_calls = 0
109 self.columns_seeded = 0
111 def seed_columns(self, fact_contexts: Sequence[FactContext]) -> dict[str, int]:
112 """Compute every kernel-backed fact for the whole chunk, in a couple of FFI crossings.
114 The short-variant shape facts are returned as columns only and not prefilled into each context's
115 memo as nothing reads them through ``get_fact``. The overlap_feature and contain_feature are
116 different, as every positional fact declares ``requires=("overlap_feature",)``, those two are
117 additionally prefilled into each memo. This per-context fan-out is the single most expensive part of
118 this strategy, which is why it is confined to the two facts that genuinely need it.
120 Args:
121 fact_contexts (Sequence[FactContext]): The chunk's contexts, batch-index order.
123 Returns:
124 dict[str, int]: Fact name -> bit column for the whole chunk.
125 """
126 context_count = len(fact_contexts)
127 if not context_count:
128 return {}
130 variant_mins: list[int] = []
131 variant_maxs: list[int] = []
132 feature_starts: list[int] = []
133 feature_ends: list[int] = []
134 reference_lengths: list[int] = []
135 alternate_lengths: list[int] = []
136 short_column = 0
137 for context_index, fact_context in enumerate(fact_contexts):
138 variant_min, variant_max = fact_context.variant_span
139 variant_mins.append(variant_min)
140 variant_maxs.append(variant_max)
141 feature = fact_context.overlap.feature
142 feature_starts.append(feature.start)
143 feature_ends.append(feature.end)
144 variant = fact_context.overlap.overlapping_feature
145 reference_lengths.append(len((variant.reference_allele or "").replace(EMPTY_ALLELE, "")))
146 alternate_lengths.append(len((variant.alternate_allele or "").replace(EMPTY_ALLELE, "")))
147 if not isinstance(variant, StructuralVariationAllele): 147 ↛ 137line 147 didn't jump to line 137 because the condition on line 147 was always true
148 short_column |= 1 << context_index
150 shape_masks = batch_variant_shapes(reference_lengths, alternate_lengths)
151 overlap_bitmap = batch_overlap_span(variant_mins, variant_maxs, feature_starts, feature_ends)
152 contain_bitmap = batch_contain_span(variant_mins, variant_maxs, feature_starts, feature_ends)
153 self.kernel_calls += 3
155 columns: dict[str, int] = {
156 fact_name: int.from_bytes(shape_masks[mask_index], "little") & short_column
157 for fact_name, mask_index in _SHORT_SHAPE_FACTS
158 }
159 # The kernel answers the length comparison for every overlap in the chunk, including any
160 # structural ones. `requires=("is_short",)` is what makes those answers False in the
161 # ordinary path, but a seeded column bypasses the decorator's guard entirely. So the gate
162 # has to be reapplied here. Without it a structural allele whose ref/alt strings happen to
163 # differ in length might be seeded as a short insertion and the kernel path would disagree
164 # with every other annotator.
165 columns["is_short"] = short_column
167 overlap_column = int.from_bytes(overlap_bitmap, "little")
168 contain_column = int.from_bytes(contain_bitmap, "little")
169 columns["contain_feature"] = contain_column
171 # We also add in the zone map columns, if a zone map is attached.
172 zone_map_cache = self.annotator_context.zone_map_cache
173 if zone_map_cache is not None:
174 columns.update(zone_map_cache.columns(fact_contexts))
176 # When a zone map is attached it has already answered the `overlap_feature` fact, so the kernel's
177 # answer is redundant.
178 if zone_map_cache is None:
179 columns["overlap_feature"] = overlap_column
180 for context_index, fact_context in enumerate(fact_contexts):
181 bit = 1 << context_index
182 fact_context.prefill({"overlap_feature": bool(overlap_column & bit)})
183 self.columns_seeded += context_count * len(columns)
184 return columns