Coverage for src/python/ensembl/vep/models/sequence/slice.py: 100%
64 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"""Slice class."""
16from __future__ import annotations
18import logging
19from copy import deepcopy
20from functools import cached_property
21from threading import RLock
22from typing import TYPE_CHECKING
24from attrs import define, field
26from ensembl.vep.common import Strand, UnsafeSetterMixin, invalidates, reverse_complement
27from ensembl.vep.models.sequence.coord_system import CoordSystem
29if TYPE_CHECKING:
30 from ensembl.vep.sources.sequence_source import SequenceSource
32logger = logging.getLogger(__name__)
35@define(kw_only=True, auto_attribs=True)
36class Slice(UnsafeSetterMixin):
37 """Represents a genomic region on a sequence.
39 Attributes:
40 coord_system (CoordSystem): Coordinate system.
41 seq_region_name (str): Sequence region name.
42 start (int): Start position relative to sequence region.
43 end (int): End position relative to sequence region.
44 strand (Strand): Slice orientation relative to sequence region.
45 seq (str | None): Sequence of the slice.
46 seq_region_length (int | None): Sequence region length.
47 sequence_source (SequenceSource | None): Lazy sequence provider.
48 """
50 coord_system: CoordSystem
51 seq_region_name: str = field(on_setattr=invalidates("_seq", "_seq_region_length"))
52 start: int = field(on_setattr=invalidates("_seq"))
53 end: int = field(on_setattr=invalidates("_seq"))
54 strand: Strand = field(on_setattr=invalidates("_seq"))
55 sequence_source: SequenceSource | None = field(
56 default=None, repr=False, on_setattr=invalidates("_seq", "_seq_region_length")
57 )
58 _lock: RLock = field(factory=RLock, init=False, repr=False)
60 @property
61 def seq(self) -> str | None:
62 """Public accessor for the _seq
64 Returns:
65 str | None: The resolved sequence, or None if unavailable.
66 """
67 return self._seq
69 @cached_property
70 def _seq(self) -> str | None:
71 """Resolve the sequence lazily from the attached sequence source.
73 Returns:
74 str | None: The resolved sequence, or None if unavailable.
75 """
77 with self._lock:
78 if self.sequence_source is None:
79 return None
81 return self.sequence_source.get_sequence_by_start_end_strand(
82 self.seq_region_name,
83 self.start,
84 self.end,
85 strand=self.strand,
86 )
88 def subseq(self, start: int, end: int, strand: Strand = Strand.FORWARD) -> str | None:
89 """Return the sequence of a span given in slice-relative coordinates.
91 A span inside a linear, source-backed slice is read straight from the source, so a feature
92 on a whole-chromosome slice never materialises the chromosome. Anything else -- a circular
93 slice, whose span may wrap the origin, or a span reaching outside this one -- is cut from
94 ``seq``.
96 Args:
97 start (int): Span start relative to the slice, 1-based inclusive.
98 end (int): Span end relative to the slice, 1-based inclusive.
99 strand (Strand): Orientation of the returned sequence relative to the slice.
101 Returns:
102 str | None: The span sequence, or None if the slice has no sequence or no strand to
103 measure the span against.
104 """
106 if self.strand == Strand.FORWARD:
107 span_start, span_end = self.start + start - 1, self.start + end - 1
108 elif self.strand == Strand.REVERSE:
109 # Relative position 1 is the slice's genomic end, so the span is measured back from it.
110 span_start, span_end = self.end - end + 1, self.end - start + 1
111 else:
112 logger.warning("Cannot obtain subseq for a slice on an unknown strand.")
113 return None
115 if (
116 self.sequence_source is not None
117 and not self.is_circular()
118 and 1 <= start <= end <= self.end - self.start + 1
119 ):
120 # Reverse-complemented once if exactly one of the slice and the request is reversed.
121 flipped = (self.strand == Strand.REVERSE) != (strand == Strand.REVERSE)
122 return self.sequence_source.get_sequence_by_start_end_strand(
123 self.seq_region_name,
124 span_start,
125 span_end,
126 strand=Strand.REVERSE if flipped else Strand.FORWARD,
127 )
129 slice_seq = self.seq
130 if slice_seq is None:
131 return None
132 span_seq = slice_seq[start - 1 : end]
133 if strand == Strand.REVERSE:
134 return reverse_complement(span_seq)
135 return span_seq
137 @property
138 def seq_region_length(self) -> int | None:
139 """Public accessor for the _seq_region_length.
141 Returns:
142 int | None: The sequence region length, or None if unavailable.
143 """
144 return self._seq_region_length
146 @cached_property
147 def _seq_region_length(self) -> int | None:
148 """Resolve the sequence region length from the attached sequence source.
150 Returns:
151 int | None: The sequence region length, or None if unavailable.
152 """
154 with self._lock:
155 if self.sequence_source is None:
156 return None
158 return self.sequence_source.get_seq_region_length(self.seq_region_name)
160 def __deepcopy__(self, memo: dict[int, object]) -> Slice:
161 """Create a deepcopy without copying the internal lock.
163 Args:
164 memo (dict[int, object]): Deepcopy memoization map.
166 Returns:
167 Slice: The copied slice instance.
168 """
170 copied = type(self)(
171 coord_system=deepcopy(self.coord_system, memo),
172 seq_region_name=self.seq_region_name,
173 start=self.start,
174 end=self.end,
175 strand=self.strand,
176 sequence_source=self.sequence_source,
177 )
179 memo[id(self)] = copied
180 return copied
182 def __eq__(self, other: object) -> bool:
183 """Compare two Slice objects and define if they are identical."""
185 if type(self) is not type(other):
186 return False
188 return (
189 self.coord_system == other.coord_system
190 and self.seq_region_name == other.seq_region_name
191 and self.start == other.start
192 and self.end == other.end
193 and self.strand == other.strand
194 )
196 def is_circular(self) -> bool:
197 """Indicate whether the slice is circular.
199 Returns:
200 bool: False for regular slices.
201 """
203 return False