Coverage for src/python/ensembl/vep/models/genic/transcript.py: 98%
436 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"""Transcript class."""
16from __future__ import annotations
18import logging
19from collections.abc import Mapping
20from typing import TYPE_CHECKING, ClassVar
21from functools import cached_property
22from threading import RLock
23from attrs import define, field
25from ensembl.vep.models import Feature
26from ensembl.vep.models.genic.cds import CDS
27from ensembl.vep.models.genic.intron import Intron
28from ensembl.vep.models.genic.translation import Translation
29from ensembl.vep.models.genic.utr import UTR
30from ensembl.vep.models.sequence import Mapper, MapperIndex
31from ensembl.vep.common import Attribute, ExonPhase, Strand, invalidates, is_resolved
32from ensembl.vep.common.codons import translate_dna
34if TYPE_CHECKING:
35 from ensembl.vep.models.genic import Gene, Exon, CDNA
37logger = logging.getLogger(__name__)
40_CODING_DERIVATIONS: tuple[str, ...] = (
41 "_coding_start",
42 "_coding_end",
43 "_first_coding_exon_index",
44 "_last_coding_exon_index",
45 "_exon_coding_start",
46 "_exon_coding_end",
47 "_cds_start_phase",
48 "_cdna_coding_start",
49 "_cdna_coding_end",
50 "_cds",
51 "_five_prime_utr",
52 "_three_prime_utr",
53 "_coding_sequence",
54 "_translated_seq",
55 "_cds_genomic_spans",
56 "_five_prime_utr_genomic_spans",
57 "_three_prime_utr_genomic_spans",
58 "_cds_mapper",
59 "_cdna_mapper",
60)
61"""Everything downstream of a coding boundary. Seeding any coding-signal source makes all of
62this stale.
64Here _coding_start/_coding_end are the first things to go, they are what every other entry below
65is computed from, and leaving them cached is what made a seed applied after a read silently have no
66effect.
68And _cds and _translation are deliberately absent as an explicitly seeded translation must survive
69a later cds seed and vice versa, the same exception ``spliced_exons``' own invalidates() list makes
70for it.
71"""
74@define(kw_only=True, auto_attribs=True)
75class Transcript(Feature):
76 """
77 Represents a transcript.
79 Attributes:
80 stable_id (str):
81 Ensembl stable transcript identifier (e.g. "ENST00000366667").
82 version (int | None):
83 Version of the stable identifier.
84 gene (Gene | None):
85 The gene to which this transcript belongs.
86 biotype (str | None):
87 Biotype of the transcript (e.g. "protein_coding").
88 spliced_exons (list[Exon]):
89 List of exons that are spliced together to form the transcript, in transcript (5' to
90 3') order, therefore, index 0 is always the first exon.
91 introns (list[Intron]):
92 Introns between consecutive spliced exons, in transcript order. Derived from
93 ``spliced_exons`` on first access rather than loaded; seed with ``seed_attrs``.
94 translation (Translation | None):
95 The translation associated with this transcript, explicitly assigned or derived from
96 whatever coding-boundary information is available.
97 alternative_translations (list[Translation] | None):
98 List of alternative translations associated with this transcript,
99 if applicable.
100 attributes (list[Attribute] | None):
101 List of attributes associated with this transcript.
102 """
104 stable_id: str
105 version: int | None = field(default=None, init=False)
106 gene: Gene | None = field(default=None, init=False)
107 biotype: str | None = field(default=None, init=False)
108 spliced_exons: list[Exon] = field(
109 factory=list,
110 init=False,
111 on_setattr=invalidates(
112 *_CODING_DERIVATIONS,
113 "_spliced_seq",
114 "_translated_seq",
115 "_introns",
116 ),
117 )
118 alternative_translations: list[Translation] | None = field(factory=list, init=False)
119 attributes: list[Attribute] | None = field(factory=list, init=False)
120 _lock: RLock = field(factory=RLock, init=False, repr=False)
122 SEED_INVALIDATES: ClassVar[Mapping[str, tuple[str, ...]]] = {
123 "cds": _CODING_DERIVATIONS,
124 "translation": _CODING_DERIVATIONS,
125 "five_prime_utr": _CODING_DERIVATIONS,
126 "three_prime_utr": _CODING_DERIVATIONS,
127 }
128 """Seeding any coding-signal source invalidates the whole coding derivation closure."""
130 @property
131 def introns(self) -> list[Intron]:
132 """Public accessor for _introns.
134 Returns:
135 list[Intron]: The introns between consecutive spliced exons, in transcript (5' to 3')
136 order.
137 """
138 return self._introns
140 @cached_property
141 def _introns(self) -> list[Intron]:
142 """Derive one intron per pair of consecutive spliced exons.
144 Every adjacent pair gets an intron, including a pair with no genomic gap between them --
145 such an intron has ``start > end`` and records adjacency only; callers that care about gap
146 size check that themselves.
148 Returns:
149 list[Intron]: The introns, in transcript (5' to 3') order.
150 """
151 with self._lock:
152 introns: list[Intron] = []
153 for prev_exon, next_exon in zip(self.spliced_exons, self.spliced_exons[1:]):
154 first, second = (
155 (next_exon, prev_exon) if self.strand == Strand.REVERSE else (prev_exon, next_exon)
156 )
157 intron = Intron(
158 start=first.end + 1, end=second.start - 1, strand=self.strand, slice=self.slice
159 )
160 intron.assign_without_hooks(prev_exon=prev_exon, next_exon=next_exon)
161 introns.append(intron)
162 return introns
164 # --------------------------------------------------------------------------
165 # Coding boundaries derivation:
166 # If a transcript is protein coding, then we should have coding boundaries. The coding boundary is
167 # captured by coding_start and coding_end and can be derived from either of the following:
168 # - CDS (attribute: cds)
169 # - UTRs (attributes: five_prime_utr and three_prime_utr)
170 # - Translation (attribute: translation)
171 # - first and last coding exon and coding start and end relative to the respective exon (attributes:
172 # first_coding_exon_index, last_coding_exon_index, exon_coding_start and exon_coding_end)
173 #
174 # Each of the above set of attributes can be derived from any of the other set but one of them must be
175 # seeded. Otherwise the transcript would not have enough information to determine its coding boundaries
176 # and be treated as non coding.
177 #
178 # The mutual dependency here (exon_coding_start can derive from cds, cds derives from
179 # exon_coding_start) never actually recurses: because the point of contention is in coding_start and
180 # coding_end function body and there we only peek at the underlying slot using is_resolved() and never
181 # instigates a computation which can recurse back to the same property.
182 #
183 # If any of the attributes directly reference the other attribute in their function body, then
184 # the other attribute should not also directly reference the first attribute in its function body. In
185 # such case is_resolved() should be used to break recursive calls.
186 # --------------------------------------------------------------------------
188 @property
189 def coding_start(self) -> int | None:
190 """Public accessor for _coding_start.
192 Returns:
193 int | None: Start of the coding region or None if not applicable.
194 """
195 return self._coding_start
197 @cached_property
198 def _coding_start(self) -> int | None:
199 """
200 Returns the start of the coding region.
202 Returns:
203 int | None: Start of the coding region or None if not applicable.
204 """
205 with self._lock:
206 if is_resolved(self, "_cds") and self.cds is not None:
207 cds = self.cds
208 return cds.start if self.strand == Strand.FORWARD else cds.end
210 if is_resolved(self, "_five_prime_utr") and self.five_prime_utr is not None:
211 five_prime_utr = self.five_prime_utr
212 return five_prime_utr.end + 1 if self.strand == Strand.FORWARD else five_prime_utr.start - 1
214 if is_resolved(self, "_translation") and self.translation is not None:
215 translation = self.translation
216 return (
217 self.start + translation.start - 1
218 if self.strand == Strand.FORWARD
219 else self.end - translation.start + 1
220 )
222 if is_resolved(self, "_first_coding_exon_index") and is_resolved(self, "_exon_coding_start"):
223 first_coding_exon_index = self.first_coding_exon_index
224 exon_coding_start = self.exon_coding_start
225 if not self.spliced_exons or first_coding_exon_index is None or exon_coding_start is None:
226 return None
227 start_exon = self.spliced_exons[first_coding_exon_index]
229 return (
230 start_exon.start + exon_coding_start - 1
231 if self.strand == Strand.FORWARD
232 else start_exon.end - exon_coding_start + 1
233 )
235 # No coding signal from any source.
236 return None
238 @property
239 def coding_end(self) -> int | None:
240 """Public accessor for _coding_end.
242 Returns:
243 int | None: End of the coding region, or None if not applicable.
244 """
245 return self._coding_end
247 @cached_property
248 def _coding_end(self) -> int | None:
249 """
250 Returns the end of the coding region.
252 Returns:
253 int | None: End of the coding region or None if not applicable.
254 """
255 with self._lock:
256 if is_resolved(self, "_cds") and self.cds is not None:
257 cds = self.cds
258 return cds.end if self.strand == Strand.FORWARD else cds.start
260 if is_resolved(self, "_three_prime_utr") and self.three_prime_utr is not None:
261 three_prime_utr = self.three_prime_utr
262 return three_prime_utr.start - 1 if self.strand == Strand.FORWARD else three_prime_utr.end + 1
264 if is_resolved(self, "_translation") and self.translation is not None:
265 translation = self.translation
266 return (
267 self.start + translation.end - 1
268 if self.strand == Strand.FORWARD
269 else self.end - translation.end + 1
270 )
272 if is_resolved(self, "_last_coding_exon_index") and is_resolved(self, "_exon_coding_end"):
273 last_coding_exon_index = self.last_coding_exon_index
274 exon_coding_end = self.exon_coding_end
275 if not self.spliced_exons or last_coding_exon_index is None or exon_coding_end is None:
276 return None
277 end_exon = self.spliced_exons[last_coding_exon_index]
279 return (
280 end_exon.start + exon_coding_end - 1
281 if self.strand == Strand.FORWARD
282 else end_exon.end - exon_coding_end + 1
283 )
285 # No coding signal from any source.
286 return None
288 @property
289 def first_coding_exon_index(self) -> int | None:
290 """Public accessor for _first_coding_exon_index.
292 Returns:
293 int | None: Index into spliced_exons of the exon where coding starts,
294 or None if the transcript has no coding signal at all.
295 """
296 return self._first_coding_exon_index
298 @cached_property
299 def _first_coding_exon_index(self) -> int | None:
300 """Derives the first coding exon's index.
302 Returns:
303 int | None: Index into spliced_exons, or None if not coding.
304 """
305 with self._lock:
306 if self.coding_start is not None:
307 target_position = self.coding_start
308 for exon_index, exon in enumerate(self.spliced_exons):
309 if exon.start <= target_position <= exon.end:
310 return exon_index
311 return None
313 @property
314 def last_coding_exon_index(self) -> int | None:
315 """Public accessor for _last_coding_exon_index.
317 Returns:
318 int | None: Index into spliced_exons of the exon where coding ends, or None
319 if the transcript has no coding signal at all.
320 """
321 return self._last_coding_exon_index
323 @cached_property
324 def _last_coding_exon_index(self) -> int | None:
325 """Derives the last coding exon's index.
327 Returns:
328 int | None: Index into spliced_exons, or None if not coding.
329 """
330 with self._lock:
331 if self.coding_end is not None:
332 target_position = self.coding_end
333 for exon_index, exon in enumerate(self.spliced_exons):
334 if exon.start <= target_position <= exon.end:
335 return exon_index
336 return None
338 @property
339 def exon_coding_start(self) -> int | None:
340 """Public accessor for _exon_coding_start.
342 Returns:
343 int | None: 1-based offset, within the first coding exon, of the first coding base,
344 or None if the transcript has no coding signal at all.
345 """
346 return self._exon_coding_start
348 @cached_property
349 def _exon_coding_start(self) -> int | None:
350 """Derives the coding start offset from the first coding exon.
352 Returns:
353 int | None: 1-based exon-relative offset, or None if not coding.
354 """
355 with self._lock:
356 if self.coding_start is not None and self.first_coding_exon_index is not None:
357 target_position = self.coding_start
358 start_exon = self.spliced_exons[self.first_coding_exon_index]
359 return (
360 (target_position - start_exon.start + 1)
361 if self.strand == Strand.FORWARD
362 else (start_exon.end - target_position + 1)
363 )
364 return None
366 @property
367 def exon_coding_end(self) -> int | None:
368 """Public accessor for _exon_coding_end.
370 Returns:
371 int | None: 1-based offset, within the last coding exon, of the last coding base, or
372 None if the transcript has no coding signal at all.
373 """
374 return self._exon_coding_end
376 @cached_property
377 def _exon_coding_end(self) -> int | None:
378 """Derives the coding end offset from the last coding exon.
380 Returns:
381 int | None: 1-based exon-relative offset, or None if not coding.
382 """
383 with self._lock:
384 if self.coding_end is not None and self.last_coding_exon_index is not None:
385 target_position = self.coding_end
386 end_exon = self.spliced_exons[self.last_coding_exon_index]
387 return (
388 (target_position - end_exon.start + 1)
389 if self.strand == Strand.FORWARD
390 else (end_exon.end - target_position + 1)
391 )
392 return None
394 @property
395 def cds_start_phase(self) -> int:
396 """Public accessor for _cds_start_phase.
398 Returns:
399 int: Bases of the first codon missing from the CDS's 5' end, 0 when it is complete.
400 """
401 return self._cds_start_phase
403 @cached_property
404 def _cds_start_phase(self) -> int:
405 """Derive the start phase from the first coding exon, as VEP does.
407 An exon's phase counts the bases of its first codon that lie before it. On the first coding
408 exon that can only mean the CDS begins part-way through a codon, and VEP pads the
409 translateable sequence with that many ``N`` (``Bio::EnsEMBL::Transcript::translateable_seq``).
410 No phase, or an unknown one, means a complete 5' end.
412 Returns:
413 int: 0, 1 or 2.
414 """
415 with self._lock:
416 first_coding_exon_index = self.first_coding_exon_index
417 if first_coding_exon_index is None:
418 return 0
419 phase = self.spliced_exons[first_coding_exon_index].phase
420 if phase in (ExonPhase.ONE, ExonPhase.TWO):
421 return phase.value
422 return 0
424 @property
425 def cdna_coding_start(self) -> int | None:
426 """Public accessor for _cdna_coding_start.
428 Returns:
429 int | None: cDNA coordinate of the start of the coding sequence, or None if not applicable.
430 """
431 return self._cdna_coding_start
433 @cached_property
434 def _cdna_coding_start(self) -> int | None:
435 """
436 Returns the start of the coding sequence with respect to the cDNA, or None if not applicable.
438 Returns:
439 int | None: cDNA coordinate of the start of the coding sequence, or None if not applicable.
440 """
441 with self._lock:
442 first_coding_exon_index = self.first_coding_exon_index
443 exon_coding_start = self.exon_coding_start
444 if first_coding_exon_index is None or exon_coding_start is None:
445 return None
447 start = 1
448 for exon_index, exon in enumerate(self.spliced_exons): 448 ↛ 456line 448 didn't jump to line 456 because the loop on line 448 didn't complete
449 if exon_index < first_coding_exon_index:
450 # if non-translateable then add the whole exon length
451 start += exon.length
452 else:
453 start += exon_coding_start - 1
454 break
456 return start
458 @property
459 def cdna_coding_end(self) -> int | None:
460 """Public accessor for _cdna_coding_end.
462 Returns:
463 int | None: cDNA coordinate of the end of the coding sequence, or None if not applicable.
464 """
465 return self._cdna_coding_end
467 @cached_property
468 def _cdna_coding_end(self) -> int | None:
469 """
470 Returns the end of the coding sequence with respect to the cDNA, or None if not applicable.
472 Returns:
473 int | None: cDNA coordinate of the end of the coding sequence, or None if not applicable.
474 """
475 with self._lock:
476 last_coding_exon_index = self.last_coding_exon_index
477 if last_coding_exon_index is None:
478 return None
479 exon_coding_end = self.exon_coding_end
481 end = 0
482 for exon_index, exon in enumerate(self.spliced_exons): 482 ↛ 493line 482 didn't jump to line 493 because the loop on line 482 didn't complete
483 if exon_index < last_coding_exon_index:
484 # if non-translateable then add the whole exon length
485 end += exon.length
486 else:
487 if exon_coding_end is None:
488 end += exon.length
489 else:
490 end += exon_coding_end
491 break
493 return end
495 @property
496 def cds(self) -> CDS | None:
497 """Public accessor for _cds.
499 Returns:
500 CDS | None: The CDS of the transcript, or None if not applicable.
501 """
502 return self._cds
504 @cached_property
505 def _cds(self) -> CDS | None:
506 """
507 Returns the CDS associated with this transcript, or None if not applicable.
509 Returns:
510 CDS | None: The CDS associated with this transcript, or None if not applicable.
511 """
512 with self._lock:
513 genomic_spans = self.cds_genomic_spans
514 first_coding_exon_index = self.first_coding_exon_index
515 last_coding_exon_index = self.last_coding_exon_index
516 if genomic_spans is None or first_coding_exon_index is None or last_coding_exon_index is None:
517 logger.warning(
518 f"Cannot compute CDS for transcript {self.stable_id} because no coding"
519 " boundary information is available."
520 )
521 return None
523 coding_exons = self.spliced_exons[first_coding_exon_index : last_coding_exon_index + 1]
524 if len(coding_exons) != len(genomic_spans):
525 # An exon clipped to nothing means the coding offsets are inconsistent with the exons.
526 logger.warning(
527 f"Cannot compute CDS for transcript {self.stable_id} because its coding boundaries"
528 " do not fit its exons."
529 )
530 return None
532 blocks: list[str] = []
533 for exon, (block_start, block_end) in zip(coding_exons, genomic_spans):
534 if exon.seq is None:
535 logger.warning(
536 f"Exon {exon.stable_id} has no sequence information,"
537 f" adding N instead of the exact sequence for this exon"
538 f" when constructing CDS sequence for transcript {self.stable_id}."
539 f" Transcript sequence may not be accurate."
540 )
541 exon_seq = "N" * exon.length
542 else:
543 exon_seq = exon.seq
545 # exon sequence is already reverse complemented
546 if self.strand == Strand.REVERSE:
547 blocks.append(exon_seq[exon.end - block_end : exon.end - block_start + 1])
548 else:
549 blocks.append(exon_seq[block_start - exon.start : block_end - exon.start + 1])
551 # Blocks are in transcript order and the sequence has already been reverse complemented
552 # so we can just join the sequences together
553 seq = "".join(blocks)
555 cds_start = min(block_start for block_start, _ in genomic_spans)
556 cds_end = max(block_end for _, block_end in genomic_spans)
557 cds = CDS(start=cds_start, end=cds_end, strand=self.strand, slice=self.slice)
558 cds.seq = seq
559 cds.transcript = self
560 if is_resolved(self, "_translation"):
561 cds.translation = self.translation
563 return cds
565 @cached_property
566 def cdna(self) -> CDNA | None:
567 """Returns the cDNA sequence for the transcript, or None if not applicable."""
568 raise NotImplementedError("Feature is not implemented yet.")
570 @property
571 def five_prime_utr(self) -> UTR | None:
572 """Public accessor for _five_prime_utr.
574 Returns:
575 The 5' UTR of the transcript, or None if not applicable.
576 """
577 return self._five_prime_utr
579 @cached_property
580 def _five_prime_utr(self) -> UTR | None:
581 """Returns the 5' UTR of the transcript, or None if not applicable.
583 Returns:
584 UTR | None: The 5' UTR, or None if the transcript is not coding or has no 5' UTR.
585 """
586 with self._lock:
587 return self._utr_envelope(five_prime=True)
589 @property
590 def three_prime_utr(self) -> UTR | None:
591 """Public accessor for _three_prime_utr.
593 Returns:
594 The 3' UTR of the transcript, or None if not applicable.
595 """
596 return self._three_prime_utr
598 @cached_property
599 def _three_prime_utr(self) -> UTR | None:
600 """Returns the 3' UTR of the transcript, or None if not applicable.
602 Returns:
603 UTR | None: The 3' UTR, or None if the transcript is not coding or has no 3' UTR.
604 """
605 with self._lock:
606 return self._utr_envelope(five_prime=False)
608 def _utr_envelope(self, *, five_prime: bool) -> UTR | None:
609 """Build the genomic envelope of one UTR.
611 We are calling it envelope because it is just the genomic span of the UTR and does not capture
612 full information. The actual UTR may span multiple exons, and therefore there are segments in the
613 between the envelope's range which is not part of the UTR but an intron.
615 Args:
616 five_prime (bool): True if we want the 5' UTR, False if we want the 3' UTR.
618 Returns:
619 UTR | None: The UTR feature, or None when the transcript is not coding or the
620 requested side is empty (the CDS runs to that end of the transcript).
621 """
622 if not self.spliced_exons:
623 return None
625 if five_prime:
626 if self.coding_start is None:
627 return None
628 if self.strand == Strand.FORWARD:
629 start, end = self.spliced_exons[0].start, self.coding_start - 1
630 else:
631 start, end = self.coding_start + 1, self.spliced_exons[0].end
632 else:
633 if self.coding_end is None:
634 return None
635 if self.strand == Strand.FORWARD:
636 start, end = self.coding_end + 1, self.spliced_exons[-1].end
637 else:
638 start, end = self.spliced_exons[-1].start, self.coding_end - 1
640 if start > end:
641 # The coding boundary runs all the way to this side of the transcript -- no UTR here.
642 logger.debug(
643 f"No {'five' if five_prime else 'three'}_prime_utr for transcript"
644 f" {self.stable_id}: the coding region runs to that end of the transcript."
645 )
646 return None
648 utr = UTR(start=start, end=end, strand=self.strand, slice=self.slice)
649 utr.transcript = self
650 return utr
652 @property
653 def translation(self) -> Translation | None:
654 """Public accessor for _translation.
656 Returns:
657 Translation | None: The transcript's translation, seeded or derived, or None if the
658 transcript has no coding signal at all.
659 """
660 return self._translation
662 @cached_property
663 def _translation(self) -> Translation | None:
664 """Returns the translation associated with this transcript, or None if not applicable.
666 Returns:
667 Translation | None: The derived translation, or None if not coding.
668 """
669 if self.coding_start is None or self.coding_end is None:
670 return None
671 coding_start, coding_end = self.coding_start, self.coding_end
673 # 1-based, measured from this transcript's own 5' end -- the exact inverse of
674 # _coding_start/_coding_end's translation-fallback branches above.
675 if self.strand == Strand.FORWARD:
676 translation_start = coding_start - self.start + 1
677 translation_end = coding_end - self.start + 1
678 else:
679 translation_start = self.end - coding_start + 1
680 translation_end = self.end - coding_end + 1
682 exon_coding_start = self.exon_coding_start if is_resolved(self, "_exon_coding_start") else None
683 exon_coding_end = self.exon_coding_end if is_resolved(self, "_exon_coding_end") else None
685 translation = Translation(
686 start=translation_start,
687 end=translation_end,
688 stable_id=f"{self.stable_id}_derived_translation",
689 exon_coding_start=exon_coding_start,
690 exon_coding_end=exon_coding_end,
691 )
692 translation.transcript = self
693 coding_sequence = self.coding_sequence
694 if coding_sequence:
695 translation.seq = translate_dna(coding_sequence)
696 translation.derived_from_coding_sequence = True
697 return translation
699 @property
700 def spliced_seq(self) -> str | None:
701 """Public accessor for _spliced_seq.
703 Returns:
704 The spliced sequence of the transcript,
705 or None if sequence information is not available for all exons.
706 """
707 return self._spliced_seq
709 @cached_property
710 def _spliced_seq(self) -> str | None:
711 """
712 The spliced sequence of the transcript,
713 or None if sequence information is not available for all exons.
715 Returns:
716 The spliced sequence of the transcript,
717 or None if sequence information is not available for all exons.
718 """
719 with self._lock:
720 seq = ""
722 for exon in self.spliced_exons:
723 if exon.seq is None:
724 logger.warning(
725 f"Exon {exon.stable_id} has no sequence information,"
726 f" adding N instead of the exact sequence for this exon"
727 f" when constructing spliced sequence for transcript {self.stable_id}."
728 f" Spliced sequence may not be accurate."
729 )
730 seq += "N" * exon.length
731 else:
732 seq += exon.seq
733 return seq if seq else None
735 @property
736 def coding_sequence(self) -> str | None:
737 """Public accessor for _coding_sequence.
739 Returns:
740 str | None: The full CDS nucleotide sequence in transcript-sense, or
741 None if the transcript is not coding or sequence is unavailable.
742 """
743 return self._coding_sequence
745 @cached_property
746 def _coding_sequence(self) -> str | None:
747 """Returns the full CDS nucleotide sequence in transcript-sense.
749 Prefixed with ``cds_start_phase`` ``N``, so that it lines up with ``cds_mapper`` offsets.
751 Returns:
752 str | None: CDS nucleotide sequence in transcript-sense orientation, or None if the
753 transcript is not coding or no sequence is available from either source.
754 """
755 with self._lock:
756 padding = "N" * self.cds_start_phase
757 cds = self.cds
758 if cds is not None and cds.seq is not None:
759 return padding + cds.seq
761 genomic_spans = self.cds_genomic_spans
762 if genomic_spans is None or self.slice is None:
763 return None
765 blocks: list[str] = [padding]
766 for block_start, block_end in genomic_spans:
767 block = self.slice.subseq(block_start, block_end, self.strand)
768 if block is None: 768 ↛ 769line 768 didn't jump to line 769 because the condition on line 768 was never true
769 return None
770 blocks.append(block)
771 return "".join(blocks)
773 @property
774 def translated_seq(self) -> str | None:
775 """Public accessor for _translated_seq.
777 Returns:
778 str | None: The translated sequence of the transcript, or None if not applicable.
779 """
780 return self._translated_seq
782 @cached_property
783 def _translated_seq(self) -> str | None:
784 """Returns the translated sequence of the transcript, or None if not applicable.
786 Returns:
787 str | None: The translated sequence of the transcript, or None if not applicable.
788 """
789 with self._lock:
790 if self.translation is not None and self.translation.seq is not None:
791 return self.translation.seq
793 coding_sequence = self.coding_sequence
794 if coding_sequence is None:
795 logger.warning(
796 f"Cannot compute translated_seq for transcript {self.stable_id} because "
797 f"translation and CDS sequence are both not available."
798 )
799 return None
801 return translate_dna(coding_sequence)
803 # ----------------------------------------------------------------------
804 # Genomic <-> CDS and Genomic <-> cDNA mapping.
805 # ----------------------------------------------------------------------
807 @property
808 def cds_genomic_spans(self) -> list[tuple[int, int]] | None:
809 """Public accessor for _cds_genomic_spans.
811 Returns:
812 list[tuple[int, int]] | None: Transcript (5' to 3') order exon blocks clipped to the
813 CDS, or None if the transcript is not coding.
814 """
815 return self._cds_genomic_spans
817 @cached_property
818 def _cds_genomic_spans(self) -> list[tuple[int, int]] | None:
819 """Returns the exon blocks clipped to the CDS, in transcript (5' to 3') order.
821 Both endpoints of every block are always given low-to-high regardless of strand, but the
822 list itself is in transcript order, matching ``spliced_exons``' own convention.
824 Returns:
825 list[tuple[int, int]] | None: Transcript-order CDS-clipped exon blocks, or None if
826 the transcript has no coding signal or no exons.
827 """
828 with self._lock:
829 first_coding_exon_index, exon_coding_start = self.first_coding_exon_index, self.exon_coding_start
830 last_coding_exon_index, exon_coding_end = self.last_coding_exon_index, self.exon_coding_end
831 if (
832 first_coding_exon_index is None
833 or last_coding_exon_index is None
834 or exon_coding_start is None
835 or exon_coding_end is None
836 or not self.spliced_exons
837 ):
838 return None
840 genomic_blocks: list[tuple[int, int]] = []
841 for exon_index, exon in enumerate(self.spliced_exons):
842 if exon_index < first_coding_exon_index or exon_index > last_coding_exon_index:
843 continue
845 block_start, block_end = exon.start, exon.end
847 if exon_index == first_coding_exon_index:
848 if self.strand == Strand.REVERSE:
849 block_end = exon.end - (exon_coding_start - 1)
850 else:
851 block_start = exon.start + exon_coding_start - 1
853 if exon_index == last_coding_exon_index:
854 if self.strand == Strand.REVERSE:
855 block_start = exon.end - exon_coding_end + 1
856 else:
857 block_end = exon.start + exon_coding_end - 1
859 if block_start <= block_end:
860 genomic_blocks.append((block_start, block_end))
862 if not genomic_blocks:
863 return None
865 return genomic_blocks
867 @property
868 def five_prime_utr_genomic_spans(self) -> list[tuple[int, int]] | None:
869 """Public accessor for _five_prime_utr_genomic_spans.
871 Returns:
872 list[tuple[int, int]] | None: Transcript (5' to 3') order exon blocks clipped to the
873 5' UTR, or None if the transcript is not coding or has no 5' UTR.
874 """
875 return self._five_prime_utr_genomic_spans
877 @cached_property
878 def _five_prime_utr_genomic_spans(self) -> list[tuple[int, int]] | None:
879 """Returns the exon blocks clipped to the 5' UTR, in transcript (5' to 3') order.
881 The mirror of cds_genomic_spans for the region upstream of the CDS in transcript sense:
882 every exon strictly before the first coding exon, plus the portion of the first coding
883 exon itself that precedes the CDS. Both endpoints of every block are always given
884 low-to-high regardless of strand, matching cds_genomic_spans' own convention.
886 Returns:
887 list[tuple[int, int]] | None: Transcript-order 5' UTR exon blocks, or None if the
888 transcript has no coding signal or no 5' UTR.
889 """
890 with self._lock:
891 if not self.cds_genomic_spans:
892 return None
893 first_coding_exon_index, exon_coding_start = self.first_coding_exon_index, self.exon_coding_start
894 if first_coding_exon_index is None or exon_coding_start is None: 894 ↛ 895line 894 didn't jump to line 895 because the condition on line 894 was never true
895 return None
897 blocks: list[tuple[int, int]] = [
898 (exon.start, exon.end) for exon in self.spliced_exons[:first_coding_exon_index]
899 ]
901 if exon_coding_start > 1:
902 first_coding_exon = self.spliced_exons[first_coding_exon_index]
903 if self.strand == Strand.REVERSE:
904 blocks.append((first_coding_exon.end - exon_coding_start + 2, first_coding_exon.end))
905 else:
906 blocks.append((first_coding_exon.start, first_coding_exon.start + exon_coding_start - 2))
908 return blocks if blocks else None
910 @property
911 def three_prime_utr_genomic_spans(self) -> list[tuple[int, int]] | None:
912 """Public accessor for _three_prime_utr_genomic_spans.
914 Returns:
915 list[tuple[int, int]] | None: Transcript (5' to 3') order exon blocks clipped to the
916 3' UTR, or None if the transcript is not coding or has no 3' UTR.
917 """
918 return self._three_prime_utr_genomic_spans
920 @cached_property
921 def _three_prime_utr_genomic_spans(self) -> list[tuple[int, int]] | None:
922 """Returns the exon blocks clipped to the 3' UTR, in transcript (5' to 3') order.
924 The mirror of _five_prime_utr_genomic_spans for the region downstream of the CDS in
925 transcript sense: the portion of the last coding exon itself that follows the CDS, plus
926 every exon strictly after it.
928 Returns:
929 list[tuple[int, int]] | None: Transcript-order 3' UTR exon blocks, or None if the
930 transcript has no coding signal or no 3' UTR.
931 """
932 with self._lock:
933 if not self.cds_genomic_spans:
934 return None
935 last_coding_exon_index, exon_coding_end = self.last_coding_exon_index, self.exon_coding_end
936 if last_coding_exon_index is None or exon_coding_end is None: 936 ↛ 937line 936 didn't jump to line 937 because the condition on line 936 was never true
937 return None
939 blocks: list[tuple[int, int]] = []
940 if exon_coding_end is not None: 940 ↛ 951line 940 didn't jump to line 951 because the condition on line 940 was always true
941 last_coding_exon = self.spliced_exons[last_coding_exon_index]
942 if self.strand == Strand.REVERSE:
943 block_end = last_coding_exon.end - exon_coding_end
944 if last_coding_exon.start <= block_end: 944 ↛ 951line 944 didn't jump to line 951 because the condition on line 944 was always true
945 blocks.append((last_coding_exon.start, block_end))
946 else:
947 block_start = last_coding_exon.start + exon_coding_end
948 if block_start <= last_coding_exon.end:
949 blocks.append((block_start, last_coding_exon.end))
951 blocks.extend((exon.start, exon.end) for exon in self.spliced_exons[last_coding_exon_index + 1 :])
953 return blocks if blocks else None
955 @property
956 def cds_mapper(self) -> Mapper | None:
957 """Public accessor for _cds_mapper.
959 Offsets are **CDS-relative**: offset 0 is the first base of the start codon, and UTR bases
960 map to nothing at all. A CDS with an incomplete 5' end starts at offset ``cds_start_phase``
961 instead, the offsets before it being VEP's ``N`` padding. Use this for anything expressed in
962 coding coordinates, e.g., codon windows, protein offsets. Its sibling ``cdna_mapper`` covers
963 the whole spliced transcript instead; the two disagree by ``cdna_coding_start - 1`` over the
964 CDS, and only ``cdna_mapper`` can place a UTR position.
966 Returns:
967 Mapper | None: The genomic<->CDS<->protein coordinate mapper for this transcript's
968 CDS, or None if the transcript is not coding.
969 """
970 return self._cds_mapper
972 @cached_property
973 def _cds_mapper(self) -> Mapper | None:
974 """Builds the Mapper for this transcript's CDS, or None if it has none.
976 Returns:
977 Mapper | None: The coordinate mapper, or None if the transcript is not coding.
978 """
979 genomic_spans = self.cds_genomic_spans
980 if genomic_spans is None or self.cds_length is None:
981 return None
982 return Mapper(
983 genomic_spans=genomic_spans,
984 strand=self.strand,
985 coding_start_offset=0,
986 # Offsets in this mapper start after the padding, so the last coding one is that far
987 # along from cds_length's own unpadded count.
988 coding_end_offset=self.cds_start_phase + self.cds_length - 1,
989 padding=self.cds_start_phase,
990 )
992 @property
993 def cdna_mapper(self) -> Mapper | None:
994 """Public accessor for _cdna_mapper.
996 Offsets are **cDNA-relative**: offset 0 is the transcript's first base, so 5' UTR, CDS and
997 3' UTR positions all map. Use this to place a variant anywhere on the mature transcript.
999 Returns:
1000 Mapper | None: The genomic<->cDNA coordinate mapper for this transcript's whole
1001 spliced sequence (5' UTR + CDS + 3' UTR), or None if it has no exons.
1002 """
1003 return self._cdna_mapper
1005 @cached_property
1006 def _cdna_mapper(self) -> Mapper | None:
1007 """Builds the Mapper for this transcript's whole spliced sequence, or None if it has no
1008 exons.
1010 The whole-transcript sibling of ``cds_mapper``, same class and mechanism, just built from
1011 every spliced exon rather than the CDS-clipped spans.
1013 A non-coding transcript still gets a mapper, since a cDNA position is meaningful without a
1014 CDS -- VEP reports one for a non-coding transcript variant. Its coding range is left empty
1015 (``coding_end_offset`` below ``coding_start_offset``), so the codon and protein methods
1016 answer None rather than reading a frame that does not exist.
1018 Returns:
1019 Mapper | None: The coordinate mapper, or None if the transcript has no exons.
1020 """
1021 if not self.spliced_exons:
1022 return None
1023 genomic_spans = [(exon.start, exon.end) for exon in self.spliced_exons]
1024 cdna_coding_start, cdna_coding_end = self.cdna_coding_start, self.cdna_coding_end
1025 if cdna_coding_start is None or cdna_coding_end is None:
1026 # No coding region: an empty range, which the codon and protein methods answer None to.
1027 cdna_coding_start, cdna_coding_end = 0, -1
1028 return Mapper(
1029 genomic_spans=genomic_spans,
1030 strand=self.strand,
1031 coding_start_offset=cdna_coding_start,
1032 coding_end_offset=cdna_coding_end,
1033 )
1035 @property
1036 def cds_length(self) -> int | None:
1037 """Number of nucleotides in the CDS.
1039 Returns:
1040 int | None: Number of nucleotides in the CDS, or None if the transcript is not coding.
1041 """
1042 genomic_spans = self.cds_genomic_spans
1043 if genomic_spans is None:
1044 return None
1045 return sum(end - start + 1 for start, end in genomic_spans)
1047 def genomic_to_cds_offset(
1048 self, genomic_position: int, *, accelerator: MapperIndex | None = None
1049 ) -> int | None:
1050 """Map a genomic position to its 0-based CDS offset.
1052 Args:
1053 genomic_position (int): A genomic position, 1-based.
1054 accelerator (MapperIndex | None): Optional O(1)-lookup accelerator for the mapping.
1056 Returns:
1057 int | None: The 0-based offset into the CDS, or None if the position is not coding.
1058 """
1059 mapper = self.cds_mapper
1060 return None if mapper is None else mapper.genomic_to_offset(genomic_position, accelerator=accelerator)
1062 def cds_offset_to_genomic(self, cds_offset: int, *, accelerator: MapperIndex | None = None) -> int | None:
1063 """Map a 0-based CDS offset to its genomic position.
1065 Args:
1066 cds_offset (int): 0-based offset into the CDS.
1067 accelerator (MapperIndex | None): Optional O(1)-lookup accelerator for the mapping.
1069 Returns:
1070 int | None: The genomic position, or None if the offset is out of range or the transcript
1071 is not coding.
1072 """
1073 mapper = self.cds_mapper
1074 return None if mapper is None else mapper.offset_to_genomic(cds_offset, accelerator=accelerator)
1076 def start_codon_genomic_spans(self) -> list[tuple[int, int]] | None:
1077 """Genomic spans of the three start-codon bases.
1079 A list rather than a single ``(min, max)`` envelope because a start codon whose three bases
1080 split across an exon-exon junction can have more than one genomic span here.
1082 Returns:
1083 list[tuple[int, int]] | None: Ascending genomic spans, or None if the transcript is
1084 not coding.
1085 """
1086 mapper = self.cds_mapper
1087 return None if mapper is None else mapper.codon_genomic_spans(0)
1089 def stop_codon_genomic_spans(self) -> list[tuple[int, int]] | None:
1090 """Genomic spans of the three stop-codon bases.
1092 A list rather than a single ``(min, max)`` envelope.
1094 Returns:
1095 list[tuple[int, int]] | None: Ascending genomic spans, or None if not coding or the
1096 CDS is shorter than 3 bases.
1097 """
1098 mapper = self.cds_mapper
1099 if mapper is None or mapper.length < 3:
1100 return None
1101 return mapper.codon_genomic_spans(mapper.length - 1)
1103 def __eq__(self, other: object) -> bool:
1104 """Compare two Transcripts using various criteria.
1106 Args:
1107 other (object): Another object to compare against.
1110 Returns:
1111 bool: True if equals, False otherwise.
1112 """
1113 if not isinstance(other, Transcript):
1114 return False
1115 return self.stable_id == other.stable_id and self.version == other.version