Coverage for src/python/ensembl/vep/caches/zone_map.py: 98%
230 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"""Cache transcript geometry as positional-fact zones.
16Zone boundaries partition a transcript and its flanks into spans with constant positional facts.
17Each zone stores a fact bitmask, allowing variant spans to be evaluated with a binary search and
18short bitwise union instead of repeated interval scans. Allele-dependent sequence facts remain
19outside the zone map.
21``ZoneMapCache`` reuses maps across variants and evicts least-recently-used maps by estimated byte
22size. Computed facts are inserted through ``FactContext.prefill`` without charging their normal
23evaluation cost.
24"""
26from __future__ import annotations
28import sys
29import time
30from array import array
31from typing import ClassVar
32from bisect import bisect_right
33from collections import OrderedDict, defaultdict
34from collections.abc import Sequence
35from threading import RLock
37from attrs import define, field, frozen
39from ensembl.vep.annotators.consequence.context.fact import FactContext
40from ensembl.vep.annotators.consequence.facts.helper import (
41 intron_offsets_to_genomic_span,
42 variant_genomic_span,
43)
44from ensembl.vep.common import DEFAULT_DISTANCE, Strand
45from ensembl.vep.models.genic import Transcript
46from ensembl.vep.models.overlap import TranscriptVariationAllele
48__all__ = [
49 "DEFAULT_ZONE_MAP_BYTES",
50 "MEMO_FACT_NAMES",
51 "SERVED_FACT_NAMES",
52 "ZoneMap",
53 "ZoneMapCache",
54]
56DEFAULT_ZONE_MAP_BYTES = 256 * 1024 * 1024
57"""Default byte budget for a zone-map cache."""
59POSITIONAL_FACT_NAMES: tuple[str, ...] = (
60 "overlap_feature",
61 "overlap_exon",
62 "overlap_intron",
63 "overlap_intron_interior",
64 "overlap_intron_boundary",
65 "overlap_donor_site",
66 "overlap_acceptor_site",
67 "overlap_donor_5th_base",
68 "overlap_donor_region",
69 "overlap_polypyrimidine_tract",
70 "overlap_splice_region",
71 "is_upstream",
72 "is_downstream",
73)
74"""Facts determined by a genomic span and fixed transcript geometry."""
77_ZONE_FACT_NAMES: tuple[str, ...] = POSITIONAL_FACT_NAMES[:-2] + (
78 "overlap_five_prime_utr",
79 "overlap_three_prime_utr",
80 "overlap_start_codon",
81 "overlap_stop_codon",
82 "overlap_cds",
83)
84"""Facts served as a union of the zone masks covered by a variant."""
86# Flank bits: a union over zones, but only meaningful when the variant misses the transcript
87# entirely, so they are not served directly out of the zone mask (see prefill()).
88_UPSTREAM_FACT_NAME = "is_upstream"
89_DOWNSTREAM_FACT_NAME = "is_downstream"
91_MASK_FACT_NAMES: tuple[str, ...] = _ZONE_FACT_NAMES + (_UPSTREAM_FACT_NAME, _DOWNSTREAM_FACT_NAME)
92_FACT_BIT: dict[str, int] = {
93 fact_name: 1 << bit_index for bit_index, fact_name in enumerate(_MASK_FACT_NAMES)
94}
96# Everything this annotator prefills, i.e. every fact computation it removes from the bill.
97SERVED_FACT_NAMES: tuple[str, ...] = _MASK_FACT_NAMES
99MEMO_FACT_NAMES: tuple[str, ...] = (
100 "overlap_feature",
101 "overlap_exon",
102 "overlap_cds",
103 "overlap_start_codon",
104 "overlap_stop_codon",
105)
106"""Facts written to each overlap memo as well as returned in columns.
108These facts appear in another fact's requirements and must remain available through ``get_fact``.
109The remaining served facts are read directly from columns by columnar annotators.
110"""
112_MASK_INTERN_CACHE: dict[int, int] = {}
113"""Interned zone masks shared by all zone maps.
115Zone masks repeat frequently. Sharing boxed integers keeps tuple lookup fast while reducing the
116memory overhead of repeated values. The cache is bounded by the masks expressible by
117``_FACT_BIT``.
118"""
121_ESTIMATED_ENTRY_OVERHEAD_BYTES = 250
122"""Fixed per-entry allowance used by ``ZoneMap.estimated_bytes``.
124The allowance covers the zone-map object, cache key, and cache bookkeeping that container sizes do
125not include. It is calibrated against ``tracemalloc`` measurements in the zone-map tests.
126"""
129_FLANK_ONLY_MARGIN = 16
130"""Distance beyond a transcript where only flank facts can hold.
132Every non-flank span a zone map records lies within the transcript's own start and end; the margin
133is slack, not a measured bound.
134"""
137def _flank_windows(
138 transcript: Transcript, upstream_distance: int, downstream_distance: int
139) -> tuple[tuple[str, int, int], ...]:
140 """Return the ``is_upstream`` and ``is_downstream`` genomic windows of a transcript.
142 The two distances need not be equal, so each window is measured from the end it belongs to:
143 on the reverse strand the 5' end is the transcript's highest coordinate.
144 """
146 before, after = upstream_distance, downstream_distance
147 if transcript.strand == Strand.REVERSE:
148 before, after = after, before
149 lower_flank = (transcript.start - before, transcript.start - 1)
150 upper_flank = (transcript.end + 1, transcript.end + after)
151 if transcript.strand == Strand.FORWARD:
152 return (("is_upstream", *lower_flank), ("is_downstream", *upper_flank))
153 return (("is_upstream", *upper_flank), ("is_downstream", *lower_flank))
156def _flank_mask(
157 transcript: Transcript,
158 min_position: int,
159 max_position: int,
160 upstream_distance: int,
161 downstream_distance: int,
162) -> int:
163 """Return the zone mask of a span that does not reach the transcript itself."""
165 mask = 0
166 for fact_name, flank_start, flank_end in _flank_windows(
167 transcript, upstream_distance, downstream_distance
168 ):
169 if min_position <= flank_end and max_position >= flank_start:
170 mask |= _FACT_BIT[fact_name]
171 return mask
174def _int64_array(values: Sequence[int]) -> array[int]:
175 """Pack zone start positions into a signed 64-bit array."""
176 return array("q", values)
179def _dedup_masks(values: Sequence[int]) -> tuple[int, ...]:
180 """Return ``values`` as a tuple, each slot pointing at one shared boxed int.
182 See ``_MASK_INTERN_CACHE``.
183 """
184 return tuple(_MASK_INTERN_CACHE.setdefault(value, value) for value in values)
187@frozen(kw_only=True, auto_attribs=True, hash=False)
188class ZoneMap:
189 """Partition a transcript and its flanks into positional-fact zones.
191 ``starts[i]`` is the first genomic position of zone ``i`` and ``masks[i]`` its fact bitmask;
192 each zone ends immediately before the next start. ``hash=False`` reflects the unhashable
193 ``array`` used for starts.
195 Attributes:
196 lowest_position (int): Lowest genomic position covered by any zone.
197 highest_position (int): Highest genomic position covered by any zone.
198 starts (array[int]): Ascending zone starts packed as signed 64-bit integers.
199 masks (tuple[int, ...]): Fact mask for each corresponding zone start.
200 inverted (tuple[tuple[int, int, int], ...]): Degenerate ``(bit, start, end)`` intervals
201 matched when a variant spans both bounds.
202 """
204 lowest_position: int
205 highest_position: int
206 starts: array[int] = field(converter=_int64_array, default=())
207 masks: tuple[int, ...] = field(converter=_dedup_masks, default=())
208 inverted: tuple[tuple[int, int, int], ...] = field(default=())
210 def lookup(self, min_position: int, max_position: int) -> int:
211 """Return the union of masks for every zone overlapped by a span.
213 Args:
214 min_position (int): Inclusive lower bound of the genomic span.
215 max_position (int): Inclusive upper bound of the genomic span.
217 Returns:
218 int: Combined mask for overlapping zones and covered inverted intervals.
219 """
220 mask = 0
221 if max_position >= self.lowest_position and min_position <= self.highest_position:
222 clipped_min = max(min_position, self.lowest_position)
223 clipped_max = min(max_position, self.highest_position)
224 start_index = bisect_right(self.starts, clipped_min) - 1
225 end_index = bisect_right(self.starts, clipped_max) - 1
226 for zone_index in range(start_index, end_index + 1):
227 mask |= self.masks[zone_index]
228 for bit, interval_start, interval_end in self.inverted:
229 if min_position <= interval_end and max_position >= interval_start:
230 mask |= bit
231 return mask
233 def estimated_bytes(self) -> int:
234 """Estimate the heap space used by this zone map.
236 Container sizes are combined with a fixed allowance for the zone-map object and cache
237 bookkeeping. Interned mask integers are not charged per map.
239 Returns:
240 int: Estimated size in bytes.
241 """
242 return (
243 sys.getsizeof(self.starts)
244 + sys.getsizeof(self.masks)
245 + sys.getsizeof(self.inverted)
246 + _ESTIMATED_ENTRY_OVERHEAD_BYTES
247 )
249 @classmethod
250 def build(
251 cls,
252 transcript: Transcript,
253 upstream_distance: int = DEFAULT_DISTANCE,
254 downstream_distance: int = DEFAULT_DISTANCE,
255 ) -> ZoneMap:
256 """Build the positional-fact zones for a transcript.
258 Splice windows use ``intron_offsets_to_genomic_span``, matching the per-variant facts.
259 Coding intervals come from the transcript's CDS, UTR, and codon mappings.
261 Args:
262 transcript (Transcript): Transcript to compile.
263 upstream_distance (int): Bases before the 5' end that ``is_upstream`` covers.
264 downstream_distance (int): Bases past the 3' end that ``is_downstream`` covers.
266 Returns:
267 ZoneMap: Compiled zone partition.
268 """
269 spans: list[tuple[int, int, int]] = [] # (bit, start, end)
270 inverted: list[tuple[int, int, int]] = []
272 def add(fact_name: str, start: int, end: int) -> None:
273 bit = _FACT_BIT[fact_name]
274 if start <= end: 274 ↛ 277line 274 didn't jump to line 277 because the condition on line 274 was always true
275 spans.append((bit, start, end))
276 else:
277 inverted.append((bit, start, end))
279 add("overlap_feature", transcript.start, transcript.end)
281 for exon in transcript.spliced_exons:
282 add("overlap_exon", exon.start, exon.end)
284 for intron in transcript.introns:
285 add("overlap_intron", intron.start, intron.end)
286 # Inverted for an intron shorter than five bases, which add() keeps out of the zones:
287 # the fact's own genomic_overlap test then matches only a span covering the whole window.
288 add("overlap_intron_interior", intron.start + 2, intron.end - 2)
289 # Genomic, strand-agnostic windows -- no strand resolution needed, unlike every
290 # offset-based span below. See overlap_intron_boundary's own docstring (position.py) for
291 # the known coverage gap relative to overlap_polypyrimidine_tract/overlap_splice_region.
292 add("overlap_intron_boundary", intron.start - 3, intron.start + 7)
293 add("overlap_intron_boundary", intron.end - 7, intron.end + 3)
294 strand = transcript.strand
295 add("overlap_donor_site", *intron_offsets_to_genomic_span(intron, strand, 1, 2, True))
296 add("overlap_acceptor_site", *intron_offsets_to_genomic_span(intron, strand, 1, 2, False))
297 add("overlap_donor_5th_base", *intron_offsets_to_genomic_span(intron, strand, 5, 5, True))
298 add("overlap_donor_region", *intron_offsets_to_genomic_span(intron, strand, 3, 6, True))
299 add(
300 "overlap_polypyrimidine_tract",
301 *intron_offsets_to_genomic_span(intron, strand, 3, 17, False),
302 )
303 add("overlap_splice_region", *intron_offsets_to_genomic_span(intron, strand, 3, 8, True))
304 add("overlap_splice_region", *intron_offsets_to_genomic_span(intron, strand, 3, 8, False))
305 # The exonic side of each boundary is strand-independent, unlike the offset spans above.
306 add("overlap_splice_region", intron.start - 3, intron.start - 1)
307 add("overlap_splice_region", intron.end + 1, intron.end + 3)
309 for fact_name, flank_start, flank_end in _flank_windows(
310 transcript, upstream_distance, downstream_distance
311 ):
312 add(fact_name, flank_start, flank_end)
314 # overlap_cds/overlap_five_prime_utr/overlap_three_prime_utr are not part of the geometry
315 # decomposition above -- they reduce to a plain interval union over an already exon-clipped
316 # genomic spans list (Transcript.cds_genomic_spans/five_prime_utr_genomic_spans/
317 # three_prime_utr_genomic_spans), added directly from that list instead.
318 for block_start, block_end in transcript.cds_genomic_spans or ():
319 add("overlap_cds", block_start, block_end)
320 for block_start, block_end in transcript.five_prime_utr_genomic_spans or ():
321 add("overlap_five_prime_utr", block_start, block_end)
322 for block_start, block_end in transcript.three_prime_utr_genomic_spans or ():
323 add("overlap_three_prime_utr", block_start, block_end)
325 for span_start, span_end in transcript.start_codon_genomic_spans() or ():
326 add("overlap_start_codon", span_start, span_end)
327 for span_start, span_end in transcript.stop_codon_genomic_spans() or ():
328 add("overlap_stop_codon", span_start, span_end)
330 if not spans: 330 ↛ 331line 330 didn't jump to line 331 because the condition on line 330 was never true
331 raise ValueError(
332 f"no positional spans to build a zone map from for transcript {transcript.stable_id!r}"
333 )
335 lowest_position = min(start for _bit, start, _end in spans)
336 highest_position = max(end for _bit, _start, end in spans)
338 cut_points = {lowest_position, highest_position + 1}
339 for _bit, start, end in spans:
340 cut_points.add(start)
341 cut_points.add(end + 1)
342 zone_boundaries = sorted(
343 point for point in cut_points if lowest_position <= point <= highest_position + 1
344 )
346 # Sweep the cut points once, counting open spans per bit, instead of testing every span
347 # against every zone: a many-exon transcript has thousands of both. Every span start and
348 # end + 1 is itself a cut point, so each event lands on a zone boundary.
349 opening_bits: dict[int, list[int]] = defaultdict(list)
350 closing_bits: dict[int, list[int]] = defaultdict(list)
351 for bit, start, end in spans:
352 opening_bits[start].append(bit)
353 closing_bits[end + 1].append(bit)
355 open_counts: dict[int, int] = defaultdict(int)
356 mask = 0
357 zone_starts: list[int] = []
358 zone_masks: list[int] = []
359 for zone_start in zone_boundaries[:-1]:
360 for bit in closing_bits.get(zone_start, ()):
361 open_counts[bit] -= 1
362 if open_counts[bit] == 0: 362 ↛ 360line 362 didn't jump to line 360 because the condition on line 362 was always true
363 mask &= ~bit
364 for bit in opening_bits.get(zone_start, ()):
365 open_counts[bit] += 1
366 mask |= bit
367 zone_starts.append(zone_start)
368 zone_masks.append(mask)
370 return cls(
371 lowest_position=lowest_position,
372 highest_position=highest_position,
373 starts=zone_starts,
374 masks=zone_masks,
375 inverted=tuple(inverted),
376 )
379@define(kw_only=True, auto_attribs=True, eq=False)
380class ZoneMapCache:
381 """Store per-transcript zone maps in a byte-budget LRU cache.
383 Maps are built outside the lock and inserted or evicted while holding it. ``eq=False``
384 preserves identity semantics for mutable shared state.
386 Attributes:
387 max_bytes (int): Byte budget for cached zone maps.
388 upstream_distance (int): Upstream distance covered by flank zones.
389 downstream_distance (int): Downstream distance covered by flank zones.
390 hit_count (int): Number of cache hits.
391 miss_count (int): Number of maps built after cache misses.
392 maps_built (int): Alias for ``miss_count``.
393 eviction_count (int): Number of entries evicted.
394 build_seconds (float): Total time spent building zone maps.
395 facts_served (int): Number of fact values prefilled without evaluation.
396 """
398 max_bytes: int = DEFAULT_ZONE_MAP_BYTES
399 upstream_distance: int = DEFAULT_DISTANCE
400 downstream_distance: int = DEFAULT_DISTANCE
401 hit_count: int = field(default=0, init=False)
402 miss_count: int = field(default=0, init=False)
403 eviction_count: int = field(default=0, init=False)
404 build_seconds: float = field(default=0.0, init=False)
405 facts_served: int = field(default=0, init=False)
406 _zone_maps: OrderedDict[tuple[str, int | None], ZoneMap] = field(
407 factory=OrderedDict, init=False, repr=False
408 )
409 _sizes: dict[tuple[str, int | None], int] = field(factory=dict, init=False, repr=False)
410 _total_bytes: int = field(default=0, init=False, repr=False)
411 _lock: RLock = field(factory=RLock, init=False, repr=False)
413 _implied_facts_by_mask: ClassVar[dict[int, tuple[str, ...]]] = {}
414 """Cache fact names implied by each zone mask.
416 The mapping depends only on ``_FACT_BIT`` and is shared by all instances. It is bounded by the
417 masks expressible by ``_MASK_FACT_NAMES``.
418 """
420 @staticmethod
421 def _implied_fact_names(mask: int) -> tuple[str, ...]:
422 """Return the fact names implied by a zone mask.
424 Args:
425 mask (int): Packed zone mask returned by ``ZoneMap.lookup``.
427 Returns:
428 tuple[str, ...]: Set facts with incompatible flank facts suppressed.
429 """
430 cache = ZoneMapCache._implied_facts_by_mask
431 implied_fact_names = cache.get(mask)
432 if implied_fact_names is None:
433 implied = [fact_name for fact_name in _ZONE_FACT_NAMES if mask & _FACT_BIT[fact_name]]
434 # Flanks are suppressed by any overlap with the feature, so they are not a plain
435 # union over the covered zones.
436 if not mask & _FACT_BIT["overlap_feature"]:
437 implied.extend(
438 fact_name
439 for fact_name in (_UPSTREAM_FACT_NAME, _DOWNSTREAM_FACT_NAME)
440 if mask & _FACT_BIT[fact_name]
441 )
442 implied_fact_names = cache[mask] = tuple(implied)
443 return implied_fact_names
445 @property
446 def maps_built(self) -> int:
447 """Return the number of zone maps built."""
448 return self.miss_count
450 def zone_map(self, transcript: Transcript) -> ZoneMap:
451 """Return a transcript's cached zone map, building it on a miss.
453 Entries are keyed by stable ID and version. Concurrent misses may build the same map more
454 than once, but insertion keeps byte accounting exact.
456 Args:
457 transcript (Transcript): Transcript to look up.
459 Returns:
460 ZoneMap: Transcript zone partition.
461 """
462 cache_key = (transcript.stable_id, transcript.version)
463 with self._lock:
464 cached = self._zone_maps.get(cache_key)
465 if cached is not None:
466 self._zone_maps.move_to_end(cache_key)
467 self.hit_count += 1
468 return cached
470 build_started = time.perf_counter()
471 zone_map = ZoneMap.build(transcript, self.upstream_distance, self.downstream_distance)
472 build_elapsed = time.perf_counter() - build_started
473 size = zone_map.estimated_bytes()
475 with self._lock:
476 if cache_key in self._sizes:
477 self._total_bytes -= self._sizes[cache_key]
478 self._zone_maps[cache_key] = zone_map
479 self._zone_maps.move_to_end(cache_key)
480 self._sizes[cache_key] = size
481 self._total_bytes += size
482 self.miss_count += 1
483 self.build_seconds += build_elapsed
484 while self._total_bytes > self.max_bytes and len(self._zone_maps) > 1:
485 evicted_key, _ = self._zone_maps.popitem(last=False)
486 self._total_bytes -= self._sizes.pop(evicted_key, 0)
487 self.eviction_count += 1
488 return zone_map
490 def clear(self) -> None:
491 """Clear the cache contents."""
492 with self._lock:
493 self._zone_maps.clear()
494 self._sizes.clear()
495 self._total_bytes = 0
497 def columns(self, fact_contexts: Sequence[FactContext]) -> dict[str, int]:
498 """Return zone-map facts as bit columns for a context batch.
500 Facts in ``MEMO_FACT_NAMES`` are also written to each context because other facts read
501 them through ``get_fact``.
503 Args:
504 fact_contexts (Sequence[FactContext]): Contexts in batch-index order.
506 Returns:
507 dict[str, int]: Fact names mapped to bit columns.
508 """
509 columns: dict[str, int] = {fact_name: 0 for fact_name in SERVED_FACT_NAMES}
511 for context_index, fact_context in enumerate(fact_contexts):
512 variant_min, variant_max = fact_context.variant_span
513 transcript = fact_context.overlap.feature
514 if (
515 variant_max < transcript.start - _FLANK_ONLY_MARGIN
516 or variant_min > transcript.end + _FLANK_ONLY_MARGIN
517 ):
518 # Most overlaps on a real genome reach the transcript only through its flank.
519 # Only the flank facts can hold there, so answer them without building a map.
520 mask = _flank_mask(
521 transcript,
522 variant_min,
523 variant_max,
524 self.upstream_distance,
525 self.downstream_distance,
526 )
527 else:
528 mask = self.zone_map(transcript).lookup(variant_min, variant_max)
529 bit = 1 << context_index
531 for fact_name in self._implied_fact_names(mask):
532 columns[fact_name] |= bit
534 # Only the facts some other fact's `requires` guard reads need to exist per overlap.
535 for context_index, fact_context in enumerate(fact_contexts):
536 bit = 1 << context_index
537 fact_context.prefill({fact_name: bool(columns[fact_name] & bit) for fact_name in MEMO_FACT_NAMES})
539 self.facts_served += len(fact_contexts) * len(columns)
540 return columns
542 def prefill(self, fact_context: FactContext[TranscriptVariationAllele]) -> None:
543 """Prefill every zone-map fact without charging evaluation cost.
545 Args:
546 fact_context (FactContext): Overlap context to prefill.
547 """
548 variant_min, variant_max = variant_genomic_span(fact_context)
549 zone_map = self.zone_map(fact_context.overlap.feature)
550 mask = zone_map.lookup(variant_min, variant_max)
552 served_values: dict[str, object] = {
553 fact_name: bool(mask & _FACT_BIT[fact_name]) for fact_name in _ZONE_FACT_NAMES
554 }
556 # The flanking facts are suppressed by any overlap with the transcript, so they are not a
557 # plain union over the covered zones.
558 variant_misses_transcript = not served_values["overlap_feature"]
559 served_values[_UPSTREAM_FACT_NAME] = variant_misses_transcript and bool(
560 mask & _FACT_BIT[_UPSTREAM_FACT_NAME]
561 )
562 served_values[_DOWNSTREAM_FACT_NAME] = variant_misses_transcript and bool(
563 mask & _FACT_BIT[_DOWNSTREAM_FACT_NAME]
564 )
566 fact_context.prefill(served_values)
567 self.facts_served += len(served_values)