Coverage for src/python/ensembl/vep/corpus/synthetic/heavy.py: 100%
101 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"""Build the dense heavy-locus synthetic corpus."""
16from __future__ import annotations
18import random
19from collections.abc import Sequence
21from ensembl.vep.common import CoordSystemLevel, Strand, invalidate
22from ensembl.vep.corpus.overlap import build_transcript_overlaps
23from ensembl.vep.corpus.registry import register_corpus
24from ensembl.vep.corpus.spec import CorpusSpec
25from ensembl.vep.corpus.synthetic.base import SyntheticCorpus
26from ensembl.vep.corpus.synthetic.components.sequence import fill_locus_sequence
27from ensembl.vep.corpus.synthetic.components.transcript import (
28 build_cds_genomic_bounds,
29 build_transcript,
30 patch_terminal_codons,
31)
32from ensembl.vep.corpus.synthetic.components.variation import (
33 _deletion,
34 _insertion,
35 _snv,
36)
37from ensembl.vep.models.genic import Gene, Transcript
38from ensembl.vep.models.sequence import CoordSystem, Slice
39from ensembl.vep.models.variation import VariationAllele
41__all__ = [
42 "build_genome",
43 "build_transcripts",
44 "build_variation_alleles",
45 "heavy_corpus",
46]
48# --------------------------------------------------------------------------
49# A heavy transcript locus.
50#
51# The four transcripts in default corpus are disjoint, which makes them useless for measuring
52# anything that shares work *between* transcripts. A real dense locus has many transcripts over
53# one gene sharing most of their internal exons and differing at the edges, so this builds that
54# shape (2 strands x 18 exon-sharing transcripts per strand):
55#
56# * three alternative first exons (alternative TSS), of different lengths, so transcripts enter
57# the shared exons in different reading frames;
58# * five constitutive internal exons present in every transcript;
59# * one cassette exon of 61bp -- deliberately not a multiple of three -- so including it shifts
60# the frame of everything downstream of it;
61# * three alternative last exons.
62#
63# 3 x 2 x 3 = 18 transcripts per locus, one locus per strand. This is the only corpus that
64# exercises multi-variant-per-transcript zone reuse (the zone map cache, caches/zone_map.py)
65# and, in a later phase, cross-transcript codon sharing.
66# --------------------------------------------------------------------------
68_CHROMOSOME_NAME = "chrHeavyLocus"
69_CHROMOSOME_LENGTH = 130000
71_FIRST_EXONS: tuple[tuple[int, int], ...] = ((0, 200), (1000, 1200), (2000, 2200))
72_CONSTITUTIVE_EXONS_UPSTREAM_OF_CASSETTE: tuple[tuple[int, int], ...] = (
73 (3000, 3150),
74 (4000, 4120),
75)
76_CASSETTE_EXON: tuple[int, int] = (4500, 4560)
77_CONSTITUTIVE_EXONS_DOWNSTREAM_OF_CASSETTE: tuple[tuple[int, int], ...] = (
78 (5000, 5180),
79 (6000, 6090),
80 (7000, 7210),
81)
82_LAST_EXONS: tuple[tuple[int, int], ...] = ((8000, 8300), (9000, 9400), (10000, 10300))
84_LOCUS_SPAN = 10300
85_FORWARD_ORIGIN = 10000
86_REVERSE_ORIGIN = 70000
87_CDS_START_OFFSET = 50
88_CDS_STOP_OFFSET = 50
89_CDS_STOP_SPACING = 6
92def _biotype(transcript_index: int) -> tuple[str, bool]:
93 """Return ``(biotype, is_coding)`` for a heavy-locus transcript, by its index in the locus.
95 Args:
96 transcript_index (int): The transcript's 0-based index within its 18-transcript locus.
98 Returns:
99 tuple[str, bool]: The transcript's biotype and whether it is coding.
100 """
101 if transcript_index % 11 == 5:
102 return "lincRNA", False
103 if transcript_index % 7 == 3:
104 return "nonsense_mediated_decay", True
105 return "protein_coding", True
108def _build_transcript(
109 synthetic_slice: Slice,
110 *,
111 strand: Strand,
112 stable_id_tag: str,
113 transcript_index: int,
114 first_exon_index: int,
115 last_exon_index: int,
116 exons_genomic_ascending: Sequence[tuple[int, int]],
117) -> Transcript:
118 """Build a single heavy-locus transcript over a fixed exon layout.
120 Args:
121 synthetic_slice (Slice): The shared synthetic-chromosome slice.
122 strand (Strand): The transcript's strand.
123 stable_id_tag (str): Prefix for the transcript's stable_id.
124 transcript_index (int): The transcript's 0-based index within its locus.
125 first_exon_index (int): Index of the alternative first exon this transcript uses.
126 last_exon_index (int): Index of the alternative last exon this transcript uses.
127 exons_genomic_ascending (Sequence[tuple[int, int]]): This transcript's exon blocks,
128 ascending
129 genomic order.
131 Returns:
132 Transcript: The constructed transcript, not yet carrying real start/stop codon sequence.
133 """
134 biotype, is_coding = _biotype(transcript_index)
136 translation_bounds: tuple[int, int] | None = None
137 if is_coding:
138 frame_index = first_exon_index if strand == Strand.FORWARD else last_exon_index
139 translation_bounds = build_cds_genomic_bounds(
140 exons_genomic_ascending,
141 strand=strand,
142 frame_index=frame_index,
143 start_offset=_CDS_START_OFFSET,
144 stop_offset=_CDS_STOP_OFFSET + _CDS_STOP_SPACING * transcript_index,
145 )
147 stable_id = f"{stable_id_tag}{transcript_index:02d}"
148 gene: Gene | None = None
149 if biotype == "nonsense_mediated_decay":
150 gene = Gene(
151 start=exons_genomic_ascending[0][0],
152 end=exons_genomic_ascending[-1][1],
153 strand=strand,
154 stable_id=f"{stable_id}_gene",
155 slice=synthetic_slice,
156 )
157 gene.biotype = biotype
159 return build_transcript(
160 stable_id=stable_id,
161 synthetic_slice=synthetic_slice,
162 strand=strand,
163 exons_genomic_ascending=exons_genomic_ascending,
164 cds_genomic_bounds=translation_bounds,
165 gene=gene,
166 )
169def build_transcripts(
170 synthetic_slice: Slice, *, origin: int, strand: Strand, stable_id_tag: str
171) -> list[Transcript]:
172 """Build 18 transcripts sharing constitutive exons over a single locus.
174 Args:
175 synthetic_slice (Slice): The shared synthetic-chromosome slice.
176 origin (int): Genomic (slice-relative) offset the locus's exon coordinates are relative
177 to.
178 strand (Strand): The strand every transcript in this locus is built on.
179 stable_id_tag (str): Prefix for each transcript's stable_id (e.g. "FWD", "REV").
181 Returns:
182 list[Transcript]: The 18 transcripts, not yet carrying real start/stop codon sequence
183 (see build_genome, which patches that in afterwards).
184 """
185 transcripts: list[Transcript] = []
186 transcript_index = 0
187 for first_exon_index, first_exon in enumerate(_FIRST_EXONS):
188 for include_cassette_exon in (False, True):
189 for last_exon_index, last_exon in enumerate(_LAST_EXONS):
190 exon_blocks = (
191 [first_exon]
192 + list(_CONSTITUTIVE_EXONS_UPSTREAM_OF_CASSETTE)
193 + ([_CASSETTE_EXON] if include_cassette_exon else [])
194 + list(_CONSTITUTIVE_EXONS_DOWNSTREAM_OF_CASSETTE)
195 + [last_exon]
196 )
197 exons_genomic_ascending = sorted(
198 (origin + block_start, origin + block_end) for block_start, block_end in exon_blocks
199 )
200 transcripts.append(
201 _build_transcript(
202 synthetic_slice,
203 strand=strand,
204 stable_id_tag=stable_id_tag,
205 transcript_index=transcript_index,
206 first_exon_index=first_exon_index,
207 last_exon_index=last_exon_index,
208 exons_genomic_ascending=exons_genomic_ascending,
209 )
210 )
211 transcript_index += 1
212 return transcripts
215def build_genome(seed: int = 31) -> tuple[Slice, tuple[Transcript, ...]]:
216 """Build the two-locus (one per strand), 36-transcript heavy-locus synthetic chromosome.
218 Mirrors ``socore.data.build_locus_genome``.
220 Args:
221 seed (int): Random seed, for reproducibility.
223 Returns:
224 tuple[Slice, tuple[Transcript, ...]]: The shared chromosome slice (with real, codon-patched
225 sequence) and all 36 transcripts (18 forward-strand, 18 reverse-strand).
226 """
227 random_generator = random.Random(seed)
228 chromosome_chars = [""] * _CHROMOSOME_LENGTH
229 fill_locus_sequence(
230 chromosome_chars,
231 1,
232 _CHROMOSOME_LENGTH,
233 random_generator,
234 bases="ACGT",
235 )
237 synthetic_slice = Slice(
238 coord_system=CoordSystem(name="chromosome", level=CoordSystemLevel.CHROMOSOME),
239 seq_region_name=_CHROMOSOME_NAME,
240 start=1,
241 end=_CHROMOSOME_LENGTH,
242 strand=Strand.FORWARD,
243 )
244 with synthetic_slice.unsafe() as unsafe_slice:
245 setattr(unsafe_slice, "_seq", "".join(chromosome_chars))
247 forward_transcripts = build_transcripts(
248 synthetic_slice, origin=_FORWARD_ORIGIN, strand=Strand.FORWARD, stable_id_tag="FWD"
249 )
250 reverse_transcripts = build_transcripts(
251 synthetic_slice, origin=_REVERSE_ORIGIN, strand=Strand.REVERSE, stable_id_tag="REV"
252 )
253 transcripts = tuple(forward_transcripts + reverse_transcripts)
255 fill_locus_sequence(
256 chromosome_chars,
257 _FORWARD_ORIGIN,
258 _FORWARD_ORIGIN + _LOCUS_SPAN,
259 random_generator,
260 )
261 fill_locus_sequence(
262 chromosome_chars,
263 _REVERSE_ORIGIN,
264 _REVERSE_ORIGIN + _LOCUS_SPAN,
265 random_generator,
266 )
267 patch_terminal_codons(chromosome_chars, transcripts)
269 with synthetic_slice.unsafe() as unsafe_slice:
270 setattr(unsafe_slice, "_seq", "".join(chromosome_chars))
272 # Unlike the default corpus's four disjoint transcripts, transcripts here legitimately
273 # share exons in different reading frames, so one transcript's real start/stop codon
274 # can land as a premature or missing stop in a sibling's frame. That is expected, not a data
275 # bug. Only the coding-sequence cache needs invalidating here.
276 for transcript in transcripts:
277 if transcript.translation is not None:
278 invalidate(transcript, "_coding_sequence")
280 return synthetic_slice, transcripts
283def build_variation_alleles(
284 synthetic_slice: Slice, step: int = 13, seed: int = 41
285) -> tuple[tuple[str, VariationAllele], ...]:
286 """Build a dense sweep of variants across each locus, so shared exons are hit repeatedly.
288 Args:
289 synthetic_slice (Slice): The chromosome slice built by build_genome.
290 step (int): Genomic spacing between consecutive sweep positions.
291 seed (int): Random seed, for reproducibility.
293 Returns:
294 tuple[tuple[str, VariationAllele], ...]: Named heavy-locus sweep variants.
296 Raises:
297 ValueError: If ``step`` is not positive.
298 """
299 if step <= 0:
300 raise ValueError(f"step must be positive, got {step}")
301 random_generator = random.Random(seed)
302 named_variants: list[tuple[str, VariationAllele]] = []
303 for origin, tag in ((_FORWARD_ORIGIN, "FWD"), (_REVERSE_ORIGIN, "REV")):
304 for sweep_index, position in enumerate(range(origin, origin + _LOCUS_SPAN, step)):
305 named_variants.append(
306 _snv(synthetic_slice, position, f"{tag}_snv{sweep_index}", random_generator)
307 )
308 if sweep_index % 3 == 0:
309 named_variants.append(_deletion(synthetic_slice, position, 1, f"{tag}_del1_{sweep_index}"))
310 if sweep_index % 5 == 0:
311 named_variants.append(_deletion(synthetic_slice, position, 3, f"{tag}_del3_{sweep_index}"))
312 if sweep_index % 7 == 0:
313 named_variants.append(
314 _insertion(synthetic_slice, position, "ACG", f"{tag}_ins3_{sweep_index}")
315 )
316 if sweep_index % 11 == 0:
317 named_variants.append(_insertion(synthetic_slice, position, "A", f"{tag}_ins1_{sweep_index}"))
318 return tuple(named_variants)
321def heavy_corpus(
322 step: int = 13,
323 seed: int = 31,
324 *,
325 sweep_seed: int = 41,
326 spec: CorpusSpec | None = None,
327) -> SyntheticCorpus:
328 """Build the heavy-locus corpus: 2 strands x 18 exon-sharing transcripts, a dense variant sweep.
330 Mirrors ``socore.data.heavy_locus_dataset``. Unlike default_corpus's four disjoint
331 transcripts, this is the only corpus that exercises multi-variant-per-transcript zone reuse
332 (the zone map cache, caches/zone_map.py) and, in a later phase, cross-transcript codon
333 sharing -- many transcripts here share the same genomic exon footprint, so a transcript's
334 zone map (or codon cache entry) built for one variant is reused by every other variant that
335 lands in the same shared exon, across every transcript sharing it.
337 Args:
338 step (int): Genomic spacing between consecutive sweep positions.
339 seed (int): Random seed for the underlying chromosome, for reproducibility.
340 sweep_seed (int): Random seed for the variant sweep's alternate bases.
341 spec (CorpusSpec | None): Construction specification retained by the corpus.
343 Returns:
344 SyntheticCorpus: The synthetic slice, its 36 transcripts, variants, and overlaps.
345 """
346 synthetic_slice, transcripts = build_genome(seed=seed)
347 named_variants = build_variation_alleles(synthetic_slice, step=step, seed=sweep_seed)
348 named_overlaps = build_transcript_overlaps(named_variants, transcripts)
349 return SyntheticCorpus(
350 synthetic_slice=synthetic_slice,
351 transcripts=transcripts,
352 named_variants=named_variants,
353 named_overlaps=named_overlaps,
354 spec=spec or CorpusSpec(kind="synthetic.heavy"),
355 )
358@register_corpus("synthetic.heavy")
359def _registered_heavy_corpus(specification: CorpusSpec) -> SyntheticCorpus:
360 """Build the registered heavy-locus synthetic corpus."""
361 return heavy_corpus(
362 step=specification.step,
363 seed=specification.heavy_genome_seed,
364 sweep_seed=specification.sweep_seed,
365 spec=specification,
366 )