Coverage for src/python/ensembl/vep/corpus/synthetic/components/variation.py: 96%

105 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"""Generate synthetic variation alleles.""" 

15 

16from __future__ import annotations 

17 

18import random 

19from collections.abc import Sequence 

20 

21from ensembl.vep.common import Strand 

22from ensembl.vep.common.constants import CANONICAL_DNA_BASES 

23from ensembl.vep.corpus.synthetic.components.sequence import random_sequence 

24from ensembl.vep.models.genic import Transcript 

25from ensembl.vep.models.sequence import Slice 

26from ensembl.vep.models.variation import VariationAllele 

27 

28__all__ = [ 

29 "boundary_variant_alleles", 

30 "fuzz_variant_alleles", 

31] 

32 

33 

34def _snv( 

35 synthetic_slice: Slice, position: int, name: str, random_generator: random.Random 

36) -> tuple[str, VariationAllele]: 

37 """Build a named single-nucleotide variant at a genomic position. 

38 

39 Args: 

40 synthetic_slice (Slice): The chromosome slice to read the reference base from. 

41 position (int): Genomic (slice-relative) position. 

42 name (str): A descriptive name for test IDs. 

43 random_generator (random.Random): Seeded random generator, for reproducibility. 

44 

45 Returns: 

46 tuple[str, VariationAllele]: The variant's name and allele. 

47 """ 

48 assert synthetic_slice.seq is not None 

49 reference_base = synthetic_slice.seq[position - 1] 

50 alternate_base = random_generator.choice([base for base in CANONICAL_DNA_BASES if base != reference_base]) 

51 return name, VariationAllele( 

52 start=position, 

53 end=position, 

54 strand=Strand.FORWARD, 

55 slice=synthetic_slice, 

56 reference_allele=reference_base, 

57 alternate_allele=alternate_base, 

58 ) 

59 

60 

61def _deletion(synthetic_slice: Slice, position: int, length: int, name: str) -> tuple[str, VariationAllele]: 

62 """Build a named deletion starting at a genomic position. 

63 

64 Args: 

65 synthetic_slice (Slice): The chromosome slice to read the deleted bases from. 

66 position (int): Genomic (slice-relative) start position of the deletion. 

67 length (int): Number of bases deleted. 

68 name (str): A descriptive name for test IDs. 

69 

70 Returns: 

71 tuple[str, VariationAllele]: The variant's name and allele. 

72 """ 

73 assert synthetic_slice.seq is not None 

74 reference_bases = synthetic_slice.seq[position - 1 : position - 1 + length] 

75 return name, VariationAllele( 

76 start=position, 

77 end=position + length - 1, 

78 strand=Strand.FORWARD, 

79 slice=synthetic_slice, 

80 reference_allele=reference_bases, 

81 alternate_allele="", 

82 ) 

83 

84 

85def _insertion( 

86 synthetic_slice: Slice, position: int, inserted_sequence: str, name: str 

87) -> tuple[str, VariationAllele]: 

88 """Build a named insertion immediately before a genomic position (``end == start - 1``). 

89 

90 Args: 

91 synthetic_slice (Slice): The chromosome slice the insertion is placed on. 

92 position (int): Genomic (slice-relative) position the insertion is placed before. 

93 inserted_sequence (str): The inserted bases. 

94 name (str): A descriptive name for test IDs. 

95 

96 Returns: 

97 tuple[str, VariationAllele]: The variant's name and allele. 

98 """ 

99 return name, VariationAllele( 

100 start=position, 

101 end=position - 1, 

102 strand=Strand.FORWARD, 

103 slice=synthetic_slice, 

104 reference_allele="", 

105 alternate_allele=inserted_sequence, 

106 ) 

107 

108 

109def _splice_boundary_variants( 

110 synthetic_slice: Slice, 

111 transcript: Transcript, 

112 random_generator: random.Random, 

113) -> list[tuple[str, VariationAllele]]: 

114 """Build the splice-site and intronic boundary variants for one transcript.""" 

115 named_variants: list[tuple[str, VariationAllele]] = [] 

116 tag = transcript.stable_id 

117 strand_step = 1 if transcript.strand == Strand.FORWARD else -1 

118 

119 for intron_index, intron in enumerate(transcript.introns): 

120 five_prime_pos, three_prime_pos = ( 

121 (intron.start, intron.end) if transcript.strand == Strand.FORWARD else (intron.end, intron.start) 

122 ) 

123 for offset in (1, 2, 3, 4, 5, 6, 8): 

124 named_variants.append( 

125 _snv( 

126 synthetic_slice, 

127 five_prime_pos + strand_step * (offset - 1), 

128 f"{tag}_intron{intron_index}_donor+{offset}", 

129 random_generator, 

130 ) 

131 ) 

132 for offset in (1, 2, 3, 5, 8, 17): 

133 named_variants.append( 

134 _snv( 

135 synthetic_slice, 

136 three_prime_pos - strand_step * (offset - 1), 

137 f"{tag}_intron{intron_index}_acceptor-{offset}", 

138 random_generator, 

139 ) 

140 ) 

141 for offset in (1, 2, 3, 4): 

142 named_variants.append( 

143 _snv( 

144 synthetic_slice, 

145 five_prime_pos - strand_step * offset, 

146 f"{tag}_intron{intron_index}_exon_before_donor{offset}", 

147 random_generator, 

148 ) 

149 ) 

150 named_variants.append( 

151 _snv( 

152 synthetic_slice, 

153 three_prime_pos + strand_step * offset, 

154 f"{tag}_intron{intron_index}_exon_after_acceptor{offset}", 

155 random_generator, 

156 ) 

157 ) 

158 deep_intron_midpoint = (intron.start + intron.end) // 2 

159 named_variants.append( 

160 _snv( 

161 synthetic_slice, 

162 deep_intron_midpoint, 

163 f"{tag}_intron{intron_index}_deep", 

164 random_generator, 

165 ) 

166 ) 

167 return named_variants 

168 

169 

170def _coding_boundary_variants( 

171 synthetic_slice: Slice, 

172 transcript: Transcript, 

173 random_generator: random.Random, 

174) -> list[tuple[str, VariationAllele]]: 

175 """Build codon, CDS, and UTR boundary variants for one coding transcript.""" 

176 named_variants: list[tuple[str, VariationAllele]] = [] 

177 tag = transcript.stable_id 

178 for codon_name, codon_spans in ( 

179 ("start", transcript.start_codon_genomic_spans()), 

180 ("stop", transcript.stop_codon_genomic_spans()), 

181 ): 

182 if codon_spans is None: 182 ↛ 183line 182 didn't jump to line 183 because the condition on line 182 was never true

183 continue 

184 for span_start, span_end in codon_spans: 

185 for position in range(span_start, span_end + 1): 

186 named_variants.append( 

187 _snv( 

188 synthetic_slice, 

189 position, 

190 f"{tag}_{codon_name}_codon_pos{position}", 

191 random_generator, 

192 ) 

193 ) 

194 # A 3bp genomic deletion/insertion at codon_spans[0][0] only actually deletes/edits 

195 # the codon when it is one contiguous genomic run. A codon split across introns cannot 

196 # be represented by a single genomic edit, so these cases are single-span only. 

197 if len(codon_spans) == 1: 197 ↛ 178line 197 didn't jump to line 178 because the condition on line 197 was always true

198 codon_start = codon_spans[0][0] 

199 named_variants.append( 

200 _deletion(synthetic_slice, codon_start, 3, f"{tag}_{codon_name}_codon_del3") 

201 ) 

202 named_variants.append( 

203 _deletion(synthetic_slice, codon_start, 1, f"{tag}_{codon_name}_codon_del1") 

204 ) 

205 named_variants.append( 

206 _insertion(synthetic_slice, codon_start, "GGG", f"{tag}_{codon_name}_codon_ins3") 

207 ) 

208 

209 cds_length = transcript.cds_length or 0 

210 for cds_offset in range(3, cds_length - 3, 17): 

211 genomic_position = transcript.cds_offset_to_genomic(cds_offset) 

212 if genomic_position is None: 212 ↛ 213line 212 didn't jump to line 213 because the condition on line 212 was never true

213 continue 

214 named_variants.append( 

215 _snv(synthetic_slice, genomic_position, f"{tag}_cds{cds_offset}", random_generator) 

216 ) 

217 named_variants.append(_deletion(synthetic_slice, genomic_position, 1, f"{tag}_cds{cds_offset}_del1")) 

218 named_variants.append(_deletion(synthetic_slice, genomic_position, 3, f"{tag}_cds{cds_offset}_del3")) 

219 named_variants.append( 

220 _insertion(synthetic_slice, genomic_position, "A", f"{tag}_cds{cds_offset}_ins1") 

221 ) 

222 named_variants.append( 

223 _insertion(synthetic_slice, genomic_position, "ACG", f"{tag}_cds{cds_offset}_ins3") 

224 ) 

225 

226 utr5_position, utr3_position = ( 

227 (transcript.start + 5, transcript.end - 5) 

228 if transcript.strand == Strand.FORWARD 

229 else (transcript.end - 5, transcript.start + 5) 

230 ) 

231 named_variants.append(_snv(synthetic_slice, utr5_position, f"{tag}_utr5_edge", random_generator)) 

232 named_variants.append(_snv(synthetic_slice, utr3_position, f"{tag}_utr3_edge", random_generator)) 

233 return named_variants 

234 

235 

236def _non_coding_boundary_variants( 

237 synthetic_slice: Slice, 

238 transcript: Transcript, 

239 random_generator: random.Random, 

240) -> list[tuple[str, VariationAllele]]: 

241 """Build the representative exonic variant for one non-coding transcript.""" 

242 return [ 

243 _snv( 

244 synthetic_slice, 

245 transcript.spliced_exons[0].start + 10, 

246 f"{transcript.stable_id}_noncoding_exon", 

247 random_generator, 

248 ) 

249 ] 

250 

251 

252def _transcript_flank_and_span_variants( 

253 synthetic_slice: Slice, 

254 transcript: Transcript, 

255 chromosome_length: int, 

256 random_generator: random.Random, 

257) -> list[tuple[str, VariationAllele]]: 

258 """Build flank and whole-transcript structural variants for one transcript.""" 

259 named_variants: list[tuple[str, VariationAllele]] = [] 

260 tag = transcript.stable_id 

261 for flank_distance in (1, 100, 4999, 5000, 5001, 8000): 

262 named_variants.append( 

263 _snv( 

264 synthetic_slice, 

265 max(1, transcript.start - flank_distance), 

266 f"{tag}_upstream{flank_distance}", 

267 random_generator, 

268 ) 

269 ) 

270 named_variants.append( 

271 _snv( 

272 synthetic_slice, 

273 min(chromosome_length, transcript.end + flank_distance), 

274 f"{tag}_downstream{flank_distance}", 

275 random_generator, 

276 ) 

277 ) 

278 named_variants.append( 

279 _deletion( 

280 synthetic_slice, 

281 transcript.start - 10, 

282 (transcript.end - transcript.start) + 20, 

283 f"{tag}_ablation", 

284 ) 

285 ) 

286 named_variants.append(_insertion(synthetic_slice, transcript.start - 10, "A" * 50, f"{tag}_elongation")) 

287 # Zero-length "insertion at a boundary" case (end == start - 1) exercised directly. 

288 named_variants.append(_insertion(synthetic_slice, transcript.start, "T", f"{tag}_insertion_at_start")) 

289 return named_variants 

290 

291 

292def boundary_variant_alleles( 

293 synthetic_slice: Slice, transcripts: Sequence[Transcript], seed: int = 11 

294) -> list[tuple[str, VariationAllele]]: 

295 """Build one variant per interesting structural offset, for every transcript. 

296 

297 Mirrors ``socore.data.boundary_variants``: every splice donor/acceptor offset, the exonic 

298 side of every splice boundary, a deep-intronic control, every start/stop codon base (plus 

299 whole-codon deletions/insertions), a sweep through the CDS, UTR edges, upstream/downstream 

300 flanks (including the 4999/5000/5001 boundary), and whole-transcript ablation/elongation. 

301 

302 Args: 

303 synthetic_slice (Slice): The chromosome slice built by the default corpus generator. 

304 transcripts (Sequence[Transcript]): The transcripts built by the default corpus generator. 

305 seed (int): Random seed, for reproducibility. 

306 

307 Returns: 

308 list[tuple[str, VariationAllele]]: Named boundary variants. 

309 """ 

310 random_generator = random.Random(seed) 

311 named_variants: list[tuple[str, VariationAllele]] = [] 

312 chromosome_length = synthetic_slice.end 

313 

314 for transcript in transcripts: 

315 named_variants.extend(_splice_boundary_variants(synthetic_slice, transcript, random_generator)) 

316 if transcript.translation is not None: 

317 named_variants.extend(_coding_boundary_variants(synthetic_slice, transcript, random_generator)) 

318 else: 

319 named_variants.extend( 

320 _non_coding_boundary_variants(synthetic_slice, transcript, random_generator) 

321 ) 

322 named_variants.extend( 

323 _transcript_flank_and_span_variants( 

324 synthetic_slice, transcript, chromosome_length, random_generator 

325 ) 

326 ) 

327 

328 return named_variants 

329 

330 

331def fuzz_variant_alleles( 

332 synthetic_slice: Slice, variant_count: int = 4000, seed: int = 23 

333) -> list[tuple[str, VariationAllele]]: 

334 """Build random variants across the whole synthetic chromosome. 

335 

336 Mirrors ``socore.data.fuzz_variants``. 

337 

338 Args: 

339 synthetic_slice (Slice): The chromosome slice built by the default corpus generator. 

340 variant_count (int): Number of fuzz variants to generate. 

341 seed (int): Random seed, for reproducibility. 

342 

343 Returns: 

344 list[tuple[str, VariationAllele]]: Named fuzz variants. 

345 

346 Raises: 

347 ValueError: If ``variant_count`` is negative. 

348 """ 

349 if variant_count < 0: 

350 raise ValueError(f"variant_count must be non-negative, got {variant_count}") 

351 random_generator = random.Random(seed) 

352 named_variants: list[tuple[str, VariationAllele]] = [] 

353 chromosome_length = synthetic_slice.end 

354 for index in range(variant_count): 

355 position = random_generator.randint(20, chromosome_length - 60) 

356 variant_kind_roll = random_generator.random() 

357 if variant_kind_roll < 0.6: 

358 named_variants.append(_snv(synthetic_slice, position, f"fuzz{index}", random_generator)) 

359 elif variant_kind_roll < 0.8: 

360 deletion_length = random_generator.choice([1, 2, 3, 4, 6, 12]) 

361 named_variants.append(_deletion(synthetic_slice, position, deletion_length, f"fuzz{index}")) 

362 else: 

363 insertion_length = random_generator.choice([1, 2, 3, 5, 9]) 

364 named_variants.append( 

365 _insertion( 

366 synthetic_slice, 

367 position, 

368 random_sequence(insertion_length, random_generator), 

369 f"fuzz{index}", 

370 ) 

371 ) 

372 return named_variants