Coverage for src/python/ensembl/vep/corpus/synthetic/components/transcript.py: 100%

96 statements  

« 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"""Build synthetic transcript model objects.""" 

15 

16from __future__ import annotations 

17 

18from collections.abc import Sequence 

19 

20from ensembl.vep.common import Strand, reverse_complement 

21from ensembl.vep.models.genic import Exon, Gene, Intron, Transcript, Translation 

22from ensembl.vep.models.sequence import Slice 

23 

24__all__ = [ 

25 "build_cds_genomic_bounds", 

26 "build_transcript", 

27 "build_translation", 

28 "calculate_cds_length", 

29 "patch_terminal_codons", 

30] 

31 

32 

33def calculate_cds_length( 

34 exons_genomic_ascending: Sequence[tuple[int, int]], 

35 cds_genomic_low: int, 

36 cds_genomic_high: int, 

37) -> int: 

38 """Return coding bases within inclusive bounds across spliced exons. 

39 

40 Args: 

41 exons_genomic_ascending (Sequence[tuple[int, int]]): Inclusive exon bounds in genomic order. 

42 cds_genomic_low (int): Inclusive lower genomic CDS boundary. 

43 cds_genomic_high (int): Inclusive upper genomic CDS boundary. 

44 

45 Returns: 

46 int: Exonic bases intersecting the CDS bounds. 

47 """ 

48 return sum( 

49 min(exon_end, cds_genomic_high) - max(exon_start, cds_genomic_low) + 1 

50 for exon_start, exon_end in exons_genomic_ascending 

51 if max(exon_start, cds_genomic_low) <= min(exon_end, cds_genomic_high) 

52 ) 

53 

54 

55def _genomic_position_at_transcript_offset( 

56 exons_genomic_ascending: Sequence[tuple[int, int]], 

57 strand: Strand, 

58 transcript_offset: int, 

59) -> int: 

60 """Return the genomic position at a zero-based spliced-transcript offset.""" 

61 if transcript_offset < 0: 

62 raise ValueError("transcript_offset must not be negative") 

63 exons_in_transcript_order = ( 

64 exons_genomic_ascending if strand == Strand.FORWARD else tuple(reversed(exons_genomic_ascending)) 

65 ) 

66 remaining = transcript_offset 

67 for exon_start, exon_end in exons_in_transcript_order[:-1]: 

68 exon_length = exon_end - exon_start + 1 

69 if remaining < exon_length: 

70 return exon_start + remaining if strand == Strand.FORWARD else exon_end - remaining 

71 remaining -= exon_length 

72 exon_start, exon_end = exons_in_transcript_order[-1] 

73 exon_length = exon_end - exon_start + 1 

74 if remaining >= exon_length: 

75 raise ValueError("transcript_offset must be within transcript length") 

76 return exon_start + remaining if strand == Strand.FORWARD else exon_end - remaining 

77 

78 

79def build_cds_genomic_bounds( 

80 exons_genomic_ascending: Sequence[tuple[int, int]], 

81 *, 

82 strand: Strand, 

83 frame_index: int, 

84 start_offset: int = 50, 

85 stop_offset: int = 50, 

86) -> tuple[int, int]: 

87 """Return CDS genomic bounds from spliced-transcript terminal offsets. 

88 

89 ``start_offset`` is measured from the transcript's 5' end and carries into later exons when 

90 the first exon is shorter. ``stop_offset`` is measured back from the 3' end and is clamped 

91 towards that end when the requested position would cross the start codon. The terminal bound 

92 is then moved towards the 5' end until the CDS length is a multiple of three. 

93 

94 Args: 

95 exons_genomic_ascending (Sequence[tuple[int, int]]): Exons in ascending genomic order. 

96 strand (Strand): Transcript strand. 

97 frame_index (int): Reading-frame index used to spread alternative starts across frames. 

98 start_offset (int): Preferred zero-based start offset from the transcript's 5' end. 

99 stop_offset (int): Preferred zero-based terminal offset back from the transcript's 3' end. 

100 

101 Returns: 

102 tuple[int, int]: Inclusive genomic ``(low, high)`` CDS bounds. 

103 

104 Raises: 

105 ValueError: If the exon layout or requested offsets cannot hold a codon. 

106 """ 

107 if not exons_genomic_ascending: 

108 raise ValueError("a coding transcript needs at least one exon") 

109 if frame_index < 0 or start_offset < 0 or stop_offset < 0: 

110 raise ValueError("CDS frame and terminal offsets must not be negative") 

111 

112 five_prime_exon = exons_genomic_ascending[0] if strand == Strand.FORWARD else exons_genomic_ascending[-1] 

113 five_prime_exon_length = five_prime_exon[1] - five_prime_exon[0] + 1 

114 adjusted_start_offset = start_offset + ((five_prime_exon_length - start_offset - frame_index) % 3) 

115 spliced_length = sum(exon_end - exon_start + 1 for exon_start, exon_end in exons_genomic_ascending) 

116 available_after_start = spliced_length - adjusted_start_offset 

117 if available_after_start < 3: 

118 raise ValueError("transcript is too short to place a complete CDS start codon") 

119 

120 maximum_stop_offset = available_after_start - 3 

121 clamped_stop_offset = min(stop_offset, maximum_stop_offset) 

122 terminal_offset = spliced_length - clamped_stop_offset - 1 

123 coding_length = terminal_offset - adjusted_start_offset + 1 

124 terminal_offset -= coding_length % 3 

125 

126 start_position = _genomic_position_at_transcript_offset( 

127 exons_genomic_ascending, 

128 strand, 

129 adjusted_start_offset, 

130 ) 

131 terminal_position = _genomic_position_at_transcript_offset( 

132 exons_genomic_ascending, 

133 strand, 

134 terminal_offset, 

135 ) 

136 cds_genomic_low = min(start_position, terminal_position) 

137 cds_genomic_high = max(start_position, terminal_position) 

138 return cds_genomic_low, cds_genomic_high 

139 

140 

141def patch_terminal_codons(chromosome_chars: list[str], transcripts: Sequence[Transcript]) -> None: 

142 """Write ATG start and TAA stop codons for every coding transcript. 

143 

144 Args: 

145 chromosome_chars (list[str]): Mutable forward-strand chromosome sequence. 

146 transcripts (Sequence[Transcript]): Transcripts whose CDS terminals are patched. 

147 

148 Raises: 

149 ValueError: If a terminal codon cannot be mapped inside its transcript CDS. 

150 """ 

151 for transcript in transcripts: 

152 if transcript.translation is None: 

153 continue 

154 transcript_cds_length = transcript.cds_length 

155 assert transcript_cds_length is not None 

156 start_positions = [transcript.cds_offset_to_genomic(offset) for offset in range(3)] 

157 stop_positions = [ 

158 transcript.cds_offset_to_genomic(transcript_cds_length - 3 + offset) for offset in range(3) 

159 ] 

160 for codon_bases, genomic_positions in (("ATG", start_positions), ("TAA", stop_positions)): 

161 if any(genomic_position is None for genomic_position in genomic_positions): 

162 raise ValueError(f"{transcript.stable_id} terminal codon falls outside its CDS") 

163 for base, genomic_position in zip(codon_bases, genomic_positions, strict=True): 

164 assert genomic_position is not None 

165 chromosome_chars[genomic_position - 1] = ( 

166 base if transcript.strand == Strand.FORWARD else reverse_complement(base) 

167 ) 

168 

169 

170def build_translation(transcript: Transcript, genomic_bounds: tuple[int, int]) -> Translation: 

171 """Build a transcript translation from inclusive genomic CDS bounds. 

172 

173 Args: 

174 transcript (Transcript): Transcript whose spliced exons contain both CDS boundaries. 

175 genomic_bounds (tuple[int, int]): Inclusive ``(low, high)`` genomic CDS bounds. 

176 

177 Returns: 

178 Translation: Translation linked to ``transcript`` with exon-relative coding offsets. 

179 

180 Raises: 

181 ValueError: If either CDS boundary falls outside the transcript's exons. 

182 """ 

183 cds_genomic_low, cds_genomic_high = genomic_bounds 

184 coding_start_position = cds_genomic_low if transcript.strand == Strand.FORWARD else cds_genomic_high 

185 coding_end_position = cds_genomic_high if transcript.strand == Strand.FORWARD else cds_genomic_low 

186 coding_start_exon = next( 

187 (exon for exon in transcript.spliced_exons if exon.start <= coding_start_position <= exon.end), 

188 None, 

189 ) 

190 coding_end_exon = next( 

191 (exon for exon in transcript.spliced_exons if exon.start <= coding_end_position <= exon.end), 

192 None, 

193 ) 

194 if coding_start_exon is None or coding_end_exon is None: 

195 raise ValueError("CDS bounds must fall within transcript exons") 

196 

197 if transcript.strand == Strand.FORWARD: 

198 exon_coding_start = coding_start_position - coding_start_exon.start + 1 

199 exon_coding_end = coding_end_position - coding_end_exon.start + 1 

200 translation_start = cds_genomic_low - transcript.start + 1 

201 translation_end = cds_genomic_high - transcript.start + 1 

202 else: 

203 exon_coding_start = coding_start_exon.end - coding_start_position + 1 

204 exon_coding_end = coding_end_exon.end - coding_end_position + 1 

205 translation_start = transcript.end - cds_genomic_high + 1 

206 translation_end = transcript.end - cds_genomic_low + 1 

207 

208 translation = Translation( 

209 start=translation_start, 

210 end=translation_end, 

211 stable_id=f"{transcript.stable_id}_translation", 

212 exon_coding_start=exon_coding_start, 

213 exon_coding_end=exon_coding_end, 

214 ) 

215 translation.transcript = transcript 

216 return translation 

217 

218 

219def build_transcript( 

220 *, 

221 stable_id: str, 

222 synthetic_slice: Slice, 

223 strand: Strand, 

224 exons_genomic_ascending: Sequence[tuple[int, int]], 

225 cds_genomic_bounds: tuple[int, int] | None, 

226 gene: Gene | None, 

227 biotype: str | None = None, 

228) -> Transcript: 

229 """Build one transcript with exons, introns, and an optional translation. 

230 

231 Args: 

232 stable_id (str): Transcript stable identifier. 

233 synthetic_slice (Slice): Sequence region shared by the transcript and its exons. 

234 strand (Strand): Transcript orientation. 

235 exons_genomic_ascending (Sequence[tuple[int, int]]): Inclusive exon bounds in genomic order. 

236 cds_genomic_bounds (tuple[int, int] | None): Inclusive CDS bounds, or ``None`` for a 

237 non-coding transcript. 

238 gene (Gene | None): Optional parent gene. 

239 biotype (str | None): Optional transcript biotype. 

240 

241 Returns: 

242 Transcript: Constructed transcript with seeded introns and translation. 

243 

244 Raises: 

245 ValueError: If a CDS boundary does not fall inside a transcript exon. 

246 """ 

247 exons_transcript_order = ( 

248 list(exons_genomic_ascending) if strand == Strand.FORWARD else list(reversed(exons_genomic_ascending)) 

249 ) 

250 spliced_exons = [ 

251 Exon( 

252 start=exon_start, 

253 end=exon_end, 

254 strand=strand, 

255 stable_id=f"{stable_id}_exon{exon_index}", 

256 slice=synthetic_slice, 

257 ) 

258 for exon_index, (exon_start, exon_end) in enumerate(exons_transcript_order) 

259 ] 

260 introns: list[Intron] = [] 

261 for prev_exon, next_exon in zip(spliced_exons, spliced_exons[1:]): 

262 first, second = (next_exon, prev_exon) if strand == Strand.REVERSE else (prev_exon, next_exon) 

263 intron = Intron(start=first.end + 1, end=second.start - 1, strand=strand, slice=synthetic_slice) 

264 intron.assign_without_hooks(prev_exon=prev_exon, next_exon=next_exon) 

265 introns.append(intron) 

266 transcript = Transcript( 

267 start=exons_genomic_ascending[0][0], 

268 end=exons_genomic_ascending[-1][1], 

269 strand=strand, 

270 stable_id=stable_id, 

271 slice=synthetic_slice, 

272 ) 

273 transcript.spliced_exons = spliced_exons 

274 transcript.seed_attrs(introns=introns) 

275 transcript.gene = gene 

276 transcript.biotype = biotype 

277 

278 if cds_genomic_bounds is not None: 

279 transcript.seed_attrs(translation=build_translation(transcript, cds_genomic_bounds)) 

280 return transcript