Coverage for src/python/ensembl/vep/corpus/describe.py: 96%

131 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"""Describing what a corpus holds, before any annotator has said anything about it. 

15 

16Shape only: chromosomes, transcripts, variants by class, how the variants pair into overlaps, and 

17the overlap listing that gives ``vep explain`` its ``--name``/``--index``/``--variant`` selectors. 

18What an annotator makes of the corpus is a run summary, and lives with the stats. 

19""" 

20 

21from __future__ import annotations 

22 

23from collections.abc import Sequence 

24 

25from attrs import frozen 

26 

27from ensembl.vep.common import Strand 

28from ensembl.vep.common.constants import EMPTY_ALLELE, UNKNOWN_VALUE 

29from ensembl.vep.corpus.base import Corpus, NamedOverlap 

30from ensembl.vep.models.genic import Transcript 

31from ensembl.vep.models.overlap import TranscriptVariationAllele 

32from ensembl.vep.models.sequence import Slice 

33from ensembl.vep.models.variation import VariationAllele 

34 

35__all__ = [ 

36 "CHROMOSOME_HEADERS", 

37 "CLASS_HEADERS", 

38 "OVERLAP_HEADERS", 

39 "TRANSCRIPT_HEADERS", 

40 "ChromosomeShape", 

41 "CorpusDescription", 

42 "OverlapEntry", 

43 "TranscriptShape", 

44 "describe_variant", 

45 "variant_class", 

46] 

47 

48CHROMOSOME_HEADERS = ("Chromosome", "Length", "Transcripts", "Variants", "Overlaps") 

49TRANSCRIPT_HEADERS = ( 

50 "Transcript", 

51 "Chromosome", 

52 "Strand", 

53 "Start", 

54 "End", 

55 "Exons", 

56 "Coding", 

57 "Biotype", 

58 "Overlaps", 

59) 

60CLASS_HEADERS = ("Class", "Variants") 

61OVERLAP_HEADERS = ("Index", "Name", "Feature", "Locus", "Alleles") 

62 

63_ALLELE_DISPLAY_LENGTH = 12 

64"""Longest allele shown in full. A whole-transcript deletion is thousands of bases, and nobody 

65selects one of those by typing it out; ``--name`` is the selector for it.""" 

66 

67 

68def _abbreviate(allele: str) -> str: 

69 """Return an allele short enough for a table cell, keeping its length visible.""" 

70 if len(allele) <= _ALLELE_DISPLAY_LENGTH: 

71 return allele 

72 return f"{allele[:_ALLELE_DISPLAY_LENGTH]}...({len(allele)}bp)" 

73 

74 

75def variant_class(allele: VariationAllele) -> str: 

76 """Return a variant's class from its trimmed alleles alone.""" 

77 reference_allele = (allele.reference_allele or "").replace(EMPTY_ALLELE, "") 

78 alternate_allele = (allele.alternate_allele or "").replace(EMPTY_ALLELE, "") 

79 if not alternate_allele: 

80 return "deletion" 

81 if not reference_allele: 

82 return "insertion" 

83 if len(reference_allele) == 1 and len(alternate_allele) == 1: 83 ↛ 85line 83 didn't jump to line 85 because the condition on line 83 was always true

84 return "SNV" 

85 return "substitution" 

86 

87 

88def describe_variant(allele: VariationAllele) -> tuple[str, str]: 

89 """Return a variant's locus and alleles, spelled the way ``--variant`` accepts them. 

90 

91 A long allele is abbreviated with its length, so the listing stays a table; the full selector 

92 for such a variant is its name. 

93 """ 

94 seq_region_name = allele.slice.seq_region_name if allele.slice is not None else UNKNOWN_VALUE 

95 reference_allele = _abbreviate(allele.reference_allele or EMPTY_ALLELE) 

96 alternate_allele = _abbreviate(allele.alternate_allele or EMPTY_ALLELE) 

97 return f"{seq_region_name}:{allele.start}", f"{reference_allele}>{alternate_allele}" 

98 

99 

100@frozen(kw_only=True, auto_attribs=True) 

101class ChromosomeShape: 

102 """One chromosome's totals. 

103 

104 Attributes: 

105 name (str): Sequence region name. 

106 length (int): Length in bases. 

107 transcripts (int): Transcripts on it. 

108 variants (int): Distinct variants on it. 

109 overlaps (int): Overlaps those variants pair into. 

110 """ 

111 

112 name: str 

113 length: int 

114 transcripts: int 

115 variants: int 

116 overlaps: int 

117 

118 @classmethod 

119 def build(cls, sequence_region: Slice, corpus: Corpus) -> ChromosomeShape: 

120 """Build one sequence region's corpus totals.""" 

121 return cls( 

122 name=sequence_region.seq_region_name, 

123 length=sequence_region.end, 

124 transcripts=sum(transcript.slice is sequence_region for transcript in corpus.transcripts), 

125 variants=sum(allele.slice is sequence_region for _name, allele in corpus.named_variants), 

126 overlaps=sum( 

127 overlap.feature.slice is sequence_region for _name, overlap in corpus.named_overlaps 

128 ), 

129 ) 

130 

131 

132@frozen(kw_only=True, auto_attribs=True) 

133class TranscriptShape: 

134 """One transcript's shape and how many overlaps reach it. 

135 

136 Attributes: 

137 stable_id (str): The transcript's stable id. 

138 chromosome (str): Sequence region name. 

139 strand (str): ``+`` or ``-``. 

140 start (int): Genomic start. 

141 end (int): Genomic end. 

142 exons (int): Exon count. 

143 coding (bool): Whether it carries a translation. 

144 biotype (str): Its own biotype, or its gene's, or empty. 

145 overlaps (int): Overlaps pairing a variant with it. 

146 """ 

147 

148 stable_id: str 

149 chromosome: str 

150 strand: str 

151 start: int 

152 end: int 

153 exons: int 

154 coding: bool 

155 biotype: str 

156 overlaps: int 

157 

158 @classmethod 

159 def build(cls, transcript: Transcript, overlap_count: int) -> TranscriptShape | None: 

160 """Build one transcript's shape, or ``None`` when it has no sequence region.""" 

161 if transcript.slice is None: 161 ↛ 162line 161 didn't jump to line 162 because the condition on line 161 was never true

162 return None 

163 biotype = transcript.biotype 

164 if biotype is None and transcript.gene is not None: 

165 biotype = transcript.gene.biotype 

166 return cls( 

167 stable_id=transcript.stable_id, 

168 chromosome=transcript.slice.seq_region_name, 

169 strand="+" if transcript.strand == Strand.FORWARD else "-", 

170 start=transcript.start, 

171 end=transcript.end, 

172 exons=len(transcript.spliced_exons), 

173 coding=transcript.translation is not None, 

174 biotype=biotype or "", 

175 overlaps=overlap_count, 

176 ) 

177 

178 

179@frozen(kw_only=True, auto_attribs=True) 

180class OverlapEntry: 

181 """One selectable overlap, as ``vep explain`` addresses it. 

182 

183 Attributes: 

184 index (int): Position in the source's order, for ``--index``. 

185 name (str): The variant's name, for ``--name``. 

186 feature (str): The transcript's stable id, for ``--transcript``. 

187 locus (str): ``CHR:POS``, the first part of a ``--variant`` selector. 

188 alleles (str): ``REF>ALT``, the rest of it, with ``-`` for an empty allele. 

189 """ 

190 

191 index: int 

192 name: str 

193 feature: str 

194 locus: str 

195 alleles: str 

196 

197 @classmethod 

198 def build(cls, index: int, name: str, overlap: TranscriptVariationAllele) -> OverlapEntry: 

199 """Build one selectable overlap entry at its corpus index.""" 

200 locus, alleles = describe_variant(overlap.overlapping_feature) 

201 return cls( 

202 index=index, 

203 name=name, 

204 feature=overlap.feature.stable_id, 

205 locus=locus, 

206 alleles=alleles, 

207 ) 

208 

209 

210@frozen(kw_only=True, auto_attribs=True) 

211class CorpusDescription: 

212 """A corpus's shape, as tables. 

213 

214 Attributes: 

215 kind (str): Which corpus kind this describes. 

216 chromosomes (tuple[ChromosomeShape, ...]): Per-chromosome totals. 

217 transcripts (tuple[TranscriptShape, ...]): Every transcript. 

218 variant_classes (tuple[tuple[str, int], ...]): Class -> distinct variants, largest first. 

219 batch_size (int): The chunk size ``transcripts_per_chunk`` was measured at. 

220 transcripts_per_chunk (float): Mean distinct transcripts per chunk of overlaps -- the 

221 number that says whether a batch shares work between overlaps or not. 

222 overlaps (tuple[OverlapEntry, ...]): The selectable overlaps, in source order. 

223 """ 

224 

225 kind: str 

226 chromosomes: tuple[ChromosomeShape, ...] 

227 transcripts: tuple[TranscriptShape, ...] 

228 variant_classes: tuple[tuple[str, int], ...] 

229 batch_size: int 

230 transcripts_per_chunk: float 

231 overlaps: tuple[OverlapEntry, ...] 

232 

233 @classmethod 

234 def build(cls, corpus: Corpus, *, select: str | None = None, batch_size: int = 256) -> CorpusDescription: 

235 """Build a description of one corpus. 

236 

237 Args: 

238 corpus (Corpus): The corpus to describe. 

239 select (str | None): Keep only the overlaps of the variant with this name. 

240 batch_size (int): Overlaps per chunk, for the sharing measure. 

241 

242 Returns: 

243 CorpusDescription: The description. 

244 """ 

245 named_overlaps = tuple(corpus.named_overlaps) 

246 overlaps_by_transcript = cls._count_overlaps_by_transcript(named_overlaps) 

247 transcript_shapes = ( 

248 TranscriptShape.build(transcript, overlaps_by_transcript.get(transcript.stable_id, 0)) 

249 for transcript in corpus.transcripts 

250 ) 

251 

252 return cls( 

253 kind=corpus.spec.kind, 

254 chromosomes=tuple( 

255 ChromosomeShape.build(sequence_region, corpus) for sequence_region in corpus.sequence_regions 

256 ), 

257 transcripts=tuple(shape for shape in transcript_shapes if shape is not None), 

258 variant_classes=cls._build_variant_classes(corpus), 

259 batch_size=batch_size, 

260 transcripts_per_chunk=cls._calculate_transcripts_per_chunk( 

261 [overlap for _name, overlap in named_overlaps], batch_size 

262 ), 

263 overlaps=tuple( 

264 OverlapEntry.build(index, name, overlap) 

265 for index, (name, overlap) in enumerate(named_overlaps) 

266 if select is None or name == select 

267 ), 

268 ) 

269 

270 @staticmethod 

271 def _count_overlaps_by_transcript(named_overlaps: Sequence[NamedOverlap]) -> dict[str, int]: 

272 """Count overlaps by transcript stable identifier.""" 

273 overlaps_by_transcript: dict[str, int] = {} 

274 for _name, overlap in named_overlaps: 

275 stable_id = overlap.feature.stable_id 

276 overlaps_by_transcript[stable_id] = overlaps_by_transcript.get(stable_id, 0) + 1 

277 return overlaps_by_transcript 

278 

279 @staticmethod 

280 def _build_variant_classes(corpus: Corpus) -> tuple[tuple[str, int], ...]: 

281 """Build variant-class totals, largest first and then alphabetically.""" 

282 class_totals: dict[str, int] = {} 

283 for _name, allele in corpus.named_variants: 

284 kind = variant_class(allele) 

285 class_totals[kind] = class_totals.get(kind, 0) + 1 

286 return tuple(sorted(class_totals.items(), key=lambda entry: (-entry[1], entry[0]))) 

287 

288 @staticmethod 

289 def _calculate_transcripts_per_chunk( 

290 overlaps: Sequence[TranscriptVariationAllele], batch_size: int 

291 ) -> float: 

292 """Calculate the mean number of distinct transcripts in an overlap chunk.""" 

293 if not overlaps or batch_size <= 0: 293 ↛ 294line 293 didn't jump to line 294 because the condition on line 293 was never true

294 return 0.0 

295 distinct_counts = [] 

296 for chunk_start in range(0, len(overlaps), batch_size): 

297 chunk = overlaps[chunk_start : chunk_start + batch_size] 

298 distinct_counts.append(len({overlap.feature.stable_id for overlap in chunk})) 

299 return sum(distinct_counts) / len(distinct_counts) 

300 

301 def chromosome_rows(self) -> list[tuple[object, ...]]: 

302 """Return the chromosome table, in ``CHROMOSOME_HEADERS`` order.""" 

303 rows: list[tuple[object, ...]] = [] 

304 for shape in self.chromosomes: 

305 rows.append((shape.name, shape.length, shape.transcripts, shape.variants, shape.overlaps)) 

306 return rows 

307 

308 def transcript_rows(self) -> list[tuple[object, ...]]: 

309 """Return the transcript table, in ``TRANSCRIPT_HEADERS`` order.""" 

310 rows: list[tuple[object, ...]] = [] 

311 for shape in self.transcripts: 

312 rows.append( 

313 ( 

314 shape.stable_id, 

315 shape.chromosome, 

316 shape.strand, 

317 shape.start, 

318 shape.end, 

319 shape.exons, 

320 "yes" if shape.coding else "no", 

321 shape.biotype, 

322 shape.overlaps, 

323 ) 

324 ) 

325 return rows 

326 

327 def class_rows(self) -> list[tuple[object, ...]]: 

328 """Return the variant-class table, in ``CLASS_HEADERS`` order.""" 

329 return list(self.variant_classes) 

330 

331 def overlap_rows(self) -> list[tuple[object, ...]]: 

332 """Return the overlap listing, in ``OVERLAP_HEADERS`` order.""" 

333 rows: list[tuple[object, ...]] = [] 

334 for entry in self.overlaps: 

335 rows.append((entry.index, entry.name, entry.feature, entry.locus, entry.alleles)) 

336 return rows