Coverage for src/python/ensembl/vep/models/sequence/mapper.py: 98%
134 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"""Genomic <-> CDS <-> protein coordinate mapping for a coding region of a transcript.
16Built from a transcript's CDS genomic spans and strand only. Stays reusable outside a
17``Transcript`` entirely.
19Always builds a small (O(exon count)) bisect index at construction:
20- prefix sums over the spans, walked in transcript order (reversed on the reverse strand)
21- the span in genomic ascending order and related prefix sums.
23Can optionally use a fully-expanded offset<->position index for O(1) lookups, at the cost of higher
24memory usage. Measured ~15MB for a titin-scale (109 kb, 363-exon) CDS, against ~52 KiB for using bisect. A
25byte-budget LRU ``caches/mapper_cache.py`` can limit memory usage for the index.
26"""
28from __future__ import annotations
30import bisect
31import logging
33from attrs import define, field
35from ensembl.vep.common import Strand
37logger = logging.getLogger(__name__)
39__all__ = ["Mapper", "MapperIndex"]
42@define(kw_only=True, auto_attribs=True)
43class MapperIndex:
44 """Index holding the offset<->genomic position mapping.
46 Turns O(log exon count) bisect lookup of Mapper into an O(1) lookup, at the cost of holding this
47 O(length) structure in memory.
49 Attributes:
50 offset_to_position (list[int]): 0-based CDS offset -> Genomic position, index ``i`` is the
51 genomic position of CDS offset ``padding + i`` (see ``Mapper.padding``).
52 position_to_offset (dict[int, int]): Genomic position -> 0-based CDS offset, inverse of
53 ``offset_to_position``.
54 """
56 offset_to_position: list[int]
57 position_to_offset: dict[int, int]
60@define(kw_only=True, auto_attribs=True)
61class Mapper:
62 """Genomic <-> offset coordinate mapping over an ordered list of genomic spans.
64 Deliberately generic: the spans can be a transcript's CDS blocks (``Transcript.cds_mapper``),
65 its whole spliced exon set (``Transcript.cdna_mapper``), or any other ordered block list.
66 "Offset" therefore means whatever the caller built the mapper from, CDS-relative in the first
67 case, cDNA-relative in the second.
69 The exception is the codon and protein methods (``codon_window``, ``codon_genomic_spans``,
70 ``offset_to_protein_offset``, ``protein_offset_to_span``). Those divide offsets by three and so
71 only mean anything on a mapper built over CDS spans; calling them on a cDNA mapper is a
72 caller error, not something this class can detect.
74 ``padding`` offsets come before the first genomic base and map to none. A CDS whose 5' end is
75 incomplete starts part-way through a codon; VEP pads it with that many ``N`` so the reading
76 frame, the codon numbering and the CDS positions it reports all count from a whole codon.
78 Attributes:
79 genomic_spans (list[tuple[int, int]]): The genomic spans, in transcript (5' to 3') order.
80 Index 0 is always the first span. Genomic-descending on the reverse strand.
81 strand (Strand): The owning transcript's strand.
82 coding_start_offset (int): 0-based offset to the first coding base
83 coding_end_offset (int): 0-based offset to the last coding base
84 padding (int): Offsets before the first genomic base, 0 for a CDS starting on a whole codon.
85 """
87 genomic_spans: list[tuple[int, int]]
88 strand: Strand
89 coding_start_offset: int
90 coding_end_offset: int
91 padding: int = 0
92 _prefix_lengths: list[int] = field(init=False, repr=False)
93 _ordered_genomic_spans: list[tuple[int, int]] = field(init=False, repr=False)
94 _ordered_span_starts: list[int] = field(init=False, repr=False)
95 _ordered_prefix_lengths: list[int] = field(init=False, repr=False)
97 def __attrs_post_init__(self) -> None:
98 """Build both bisect views: transcript order (for offset->genomic) and genomic order (for
99 genomic->offset)."""
100 prefix_lengths = [self.padding]
101 for span_start, span_end in self.genomic_spans:
102 prefix_lengths.append(prefix_lengths[-1] + (span_end - span_start + 1))
103 self._prefix_lengths = prefix_lengths
105 # Order by genomic start position ascending
106 genomic_order = sorted(range(len(self.genomic_spans)), key=lambda index: self.genomic_spans[index][0])
108 ordered_genomic_spans: list[tuple[int, int]] = []
109 ordered_span_starts: list[int] = []
110 ordered_prefix_lengths: list[int] = []
111 for index in genomic_order:
112 span = self.genomic_spans[index]
113 ordered_genomic_spans.append(span)
114 ordered_span_starts.append(span[0])
115 ordered_prefix_lengths.append(prefix_lengths[index])
116 self._ordered_genomic_spans = ordered_genomic_spans
117 self._ordered_span_starts = ordered_span_starts
118 self._ordered_prefix_lengths = ordered_prefix_lengths
120 @property
121 def length(self) -> int:
122 """Total number of nucleotides covered by ``genomic_spans``.
124 Returns:
125 int: Length in bases, ``padding`` included (just ``padding`` if ``genomic_spans`` is
126 empty). CDS length on a CDS mapper, cDNA length on a cDNA mapper.
127 """
128 return self._prefix_lengths[-1]
130 def genomic_to_offset(
131 self, genomic_position: int, *, accelerator: MapperIndex | None = None
132 ) -> int | None:
133 """Map a genomic position to its 0-based CDS/cDNA offset.
135 Args:
136 genomic_position (int): A genomic position, 1-based.
137 accelerator (MapperIndex | None): If given and it covers this CDS/cDNA, answers in O(1)
138 via dict lookup; otherwise falls back to an O(log exon count) bisect search.
140 Returns:
141 int | None: The 0-based offset into the CDS/cDNA, or None if the position is not in the CDS/cDNA.
142 """
143 if self.strand == Strand.UNKNOWN:
144 logger.warning(
145 "Strand is unknown, cannot map genomic positions with confidence. "
146 "Assuming the strand is forward."
147 )
149 if accelerator is not None:
150 return accelerator.position_to_offset.get(genomic_position)
152 span_index = bisect.bisect_right(self._ordered_span_starts, genomic_position) - 1
153 if span_index < 0:
154 return None
156 span_start, span_end = self._ordered_genomic_spans[span_index]
157 if not span_start <= genomic_position <= span_end:
158 return None
160 offset_in_span = (
161 (span_end - genomic_position)
162 if self.strand == Strand.REVERSE
163 else (genomic_position - span_start)
164 )
165 return self._ordered_prefix_lengths[span_index] + offset_in_span
167 def offset_to_genomic(self, offset: int, *, accelerator: MapperIndex | None = None) -> int | None:
168 """Map a 0-based CDS/cDNA offset to its genomic position.
170 Args:
171 offset (int): 0-based offset into the CDS/cDNA.
172 accelerator (MapperIndex | None): If given, answers in O(1) via list index; otherwise
173 falls back to an O(log exon count) bisect search.
175 Returns:
176 int | None: The genomic position, or None if the offset is out of range or padding.
177 """
178 if self.strand == Strand.UNKNOWN:
179 logger.warning(
180 "Strand is unknown, cannot map genomic positions with confidence. "
181 "Assuming the strand is forward."
182 )
184 if accelerator is not None:
185 index = accelerator.offset_to_position
186 unpadded_offset = offset - self.padding
187 return index[unpadded_offset] if 0 <= unpadded_offset < len(index) else None
189 if not self.padding <= offset < self.length:
190 return None
192 span_index = bisect.bisect_right(self._prefix_lengths, offset) - 1
193 span_start, span_end = self.genomic_spans[span_index]
194 offset_in_span = offset - self._prefix_lengths[span_index]
195 return (span_end - offset_in_span) if self.strand == Strand.REVERSE else (span_start + offset_in_span)
197 def genomic_span_to_offsets(self, min_position: int, max_position: int) -> tuple[int, int] | None:
198 """Map a genomic span ``[min_position, max_position]`` to CDS/cDNA offsets ``[low, high]``.
200 Equivalent to calling ``genomic_to_offset`` on every genomic position in the span and
201 taking the min/max of whatever is overlapping the CDS/cDNA. But instead of calling for every genomic
202 position in the span, this uses a bisect search to find the overlapping coding spans and then
203 calculates the offsets from the span's prefix sums and the portion overlapping with the span.
205 Suitable for a variant's genomic span, which may be very large if it is structural.
207 Args:
208 min_position (int): Lower bound (inclusive) of the genomic span, 1-based.
209 max_position (int): Upper bound (inclusive) of the genomic span, 1-based.
211 Returns:
212 tuple[int, int] | None: (low, high) 0-based CDS/cDNA offsets, or None if the span touches
213 no CDS/cDNA spans at all.
214 """
215 if self.strand == Strand.UNKNOWN:
216 logger.warning(
217 "Strand is unknown, cannot map genomic positions with confidence. "
218 "Assuming the strand is forward."
219 )
221 if max_position < min_position:
222 return None
224 last_index = bisect.bisect_right(self._ordered_span_starts, max_position) - 1
225 if last_index < 0:
226 return None
228 # The candidate span whose end <= min_position ended before min_position means the genomic span starts
229 # right after it), in which case the first span that can possibly overlap is the next one.
230 first_index = bisect.bisect_right(self._ordered_span_starts, min_position) - 1
231 if first_index < 0 or self._ordered_genomic_spans[first_index][1] < min_position:
232 first_index += 1
234 if first_index > last_index:
235 return None
237 # Get the offsets from the first and last overlapping CDS/cDNA spans
238 offsets: list[int] = []
239 # dict.fromkeys, not a set: it dedupes the same way when first_index == last_index but
240 # iterates in a defined order rather than hash order.
241 for index in dict.fromkeys((first_index, last_index)):
242 span_start, span_end = self._ordered_genomic_spans[index]
243 overlap_start = max(span_start, min_position)
244 overlap_end = min(span_end, max_position)
245 prefix_length = self._ordered_prefix_lengths[index]
246 if self.strand == Strand.REVERSE:
247 offsets.append(prefix_length + (span_end - overlap_end))
248 offsets.append(prefix_length + (span_end - overlap_start))
249 else:
250 offsets.append(prefix_length + (overlap_start - span_start))
251 offsets.append(prefix_length + (overlap_end - span_start))
253 if not offsets: 253 ↛ 254line 253 didn't jump to line 254 because the condition on line 253 was never true
254 return None
255 return min(offsets), max(offsets)
257 def codon_genomic_spans(self, offset: int) -> list[tuple[int, int]] | None:
258 """Genomic spans of the whole codon containing ``offset``.
260 A single ``(min, max)`` envelope silently excludes an intron the codon straddles. Therefore the
261 three individual genomic positions are grouped into maximal runs of consecutive positions, so a
262 codon split across an exon-exon junction comes back as two (or in an extreme case, three) disjoint
263 spans.
265 Args:
266 offset (int): Any 0-based CDS offset within the codon.
268 Returns:
269 list[tuple[int, int]] | None: Ascending genomic spans, or None if none of the three bases
270 map to a genomic position.
271 """
272 if offset < self.coding_start_offset or offset > self.coding_end_offset:
273 return None
275 # Get the offset of the first base of the codon containing offset
276 codon_start = max((offset // 3) * 3, self.coding_start_offset)
278 # Then determine the genomic positions of all three bases of that codon
279 genomic_positions = sorted(
280 position
281 for position in (self.offset_to_genomic(codon_start + base_index) for base_index in range(3))
282 if position is not None
283 )
284 if not genomic_positions: 284 ↛ 285line 284 didn't jump to line 285 because the condition on line 284 was never true
285 return None
287 # Group the three genomic positions into minimal number of spans
288 spans: list[tuple[int, int]] = []
289 run_start = run_end = genomic_positions[0]
290 for position in genomic_positions[1:]:
291 if position == run_end + 1:
292 run_end = position
293 else:
294 spans.append((run_start, run_end))
295 run_start = run_end = position
296 spans.append((run_start, run_end))
297 return spans
299 def codon_window(self, offsets: tuple[int, int] | None) -> tuple[int, int] | None:
300 """0-based CDS half-open offsets ``[start, end)`` extending to whole codon(s) window.
302 Args:
303 offsets (tuple[int, int] | None): ``(low, high)`` 0-based CDS offsets.
305 Returns:
306 tuple[int, int] | None: The codon-aligned window, or None if ``offsets`` is None or
307 the window is empty (e.g. the offsets range is entirely past ``length``).
308 """
309 if offsets is None or offsets[0] > self.coding_end_offset or offsets[1] < self.coding_start_offset:
310 return None
311 low_offset, high_offset = offsets
312 codon_start = max((low_offset // 3) * 3, self.coding_start_offset)
313 codon_end = min((high_offset // 3) * 3 + 3, self.coding_end_offset + 1)
314 return (codon_start, codon_end) if codon_end > codon_start else None
316 def offset_to_protein_offset(self, offset: int) -> int | None:
317 """Map a 0-based CDS offset to its 0-based protein (residue) offset.
319 Args:
320 offset (int): 0-based offset into the CDS.
322 Returns:
323 int | None: 0-based residue index, or None if ``offset`` is out of range.
324 """
325 if not 0 <= offset < self.length:
326 return None
327 return offset // 3
329 def protein_offset_to_span(self, protein_offset: int) -> tuple[int, int] | None:
330 """Map a 0-based protein (residue) offset to its codon's CDS-offset span.
332 Args:
333 protein_offset (int): 0-based residue index.
335 Returns:
336 tuple[int, int] | None: Inclusive 0-based ``(low, high)`` CDS-offset span of the
337 residue's codon (clipped to ``length`` for a partial final codon), or None if
338 ``protein_offset`` is negative or starts beyond the CDS.
339 """
340 low = protein_offset * 3
341 if protein_offset < 0 or low >= self.length:
342 return None
343 return low, min(low + 2, self.length - 1)
345 def build_index(self) -> MapperIndex:
346 """Build the O(length) accelerator.
348 Returns:
349 MapperIndex: The fully-expanded offset<->genomic position structures.
350 """
351 genomic_positions: list[int] = []
352 for span_start, span_end in self.genomic_spans:
353 span_positions = (
354 range(span_end, span_start - 1, -1)
355 if self.strand == Strand.REVERSE
356 else range(span_start, span_end + 1)
357 )
358 genomic_positions.extend(span_positions)
359 position_to_offset = {
360 position: offset for offset, position in enumerate(genomic_positions, start=self.padding)
361 }
362 return MapperIndex(offset_to_position=genomic_positions, position_to_offset=position_to_offset)