Coverage for src/python/ensembl/vep/stats/summary.py: 95%

191 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"""Term-level annotation run summaries. 

15 

16Most of it is already on the model: ``Variation.class_so_term`` is the variant-classes chart and 

17``Variation.most_severe_consequence`` the most-severe chart. The collector adds only what is 

18genuinely cross-variant -- every consequence, the coding ones, variants by chromosome and where 

19along it they fall -- and the run's own metadata. Cheap enough to be on by default: about a 

20microsecond per overlap, against a fact layer called ninety times as often. 

21""" 

22 

23from __future__ import annotations 

24 

25from collections.abc import Mapping 

26 

27from attrs import define, field, frozen 

28 

29from ensembl.vep.annotators.consequence.rules.rulesets import coding_terms 

30from ensembl.vep.common.constants import UNKNOWN_VALUE 

31from ensembl.vep.models.variation import Variation 

32from ensembl.vep.render.chart import Slice 

33from ensembl.vep.render.report import ChartKind, ReportSection 

34 

35__all__ = ["POSITION_BINS", "RunSummary", "RunSummaryCollector", "RunSummaryDelta"] 

36 

37POSITION_BINS = 10 

38"""How many equal bins a chromosome's observed span is divided into for the position chart.""" 

39 

40_METADATA_HEADERS = ("Key", "Value") 

41_CHROMOSOME_HEADERS = ("Chromosome", "Variants") 

42_POSITION_HEADERS = ("Chromosome", "Bin", "From", "To", "Variants") 

43 

44 

45def _counts(totals: Mapping[str, int]) -> tuple[tuple[str, int], ...]: 

46 """Return counts largest first, then by name, so a chart reads top-down.""" 

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

48 

49 

50def _term_slices(counts: tuple[tuple[str, int], ...]) -> tuple[Slice, ...]: 

51 """Return term counts as slices, each taking its colour from the chart's default palette.""" 

52 return tuple(Slice(label=term, value=count) for term, count in counts) 

53 

54 

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

56class RunSummary: 

57 """Term-level summary of an annotation run. 

58 

59 Attributes: 

60 variants (int): Variations observed. 

61 alleles (int): Alternate alleles across them. 

62 overlaps (int): Feature overlaps across those alleles. 

63 variant_classes (tuple[tuple[str, int], ...]): Class SO term -> variants. 

64 most_severe (tuple[tuple[str, int], ...]): Most severe term -> variants. 

65 consequences (tuple[tuple[str, int], ...]): Every term -> overlaps carrying it. 

66 coding_consequences (tuple[tuple[str, int], ...]): The coding subset of the above. 

67 by_chromosome (tuple[tuple[str, int], ...]): Chromosome -> variants. 

68 positions (tuple[tuple[str, int, int, int, int], ...]): Chromosome, bin, from, to, 

69 variants -- the distribution along each chromosome's observed span. Streaming merges 

70 retain exact spans and totals; bin allocation is estimated if a later batch expands a 

71 chromosome's span. 

72 metadata (tuple[tuple[str, str], ...]): The run's own facts: command, counts, timings. 

73 """ 

74 

75 variants: int = field(default=0) 

76 alleles: int = field(default=0) 

77 overlaps: int = field(default=0) 

78 variant_classes: tuple[tuple[str, int], ...] = field(default=()) 

79 most_severe: tuple[tuple[str, int], ...] = field(default=()) 

80 consequences: tuple[tuple[str, int], ...] = field(default=()) 

81 coding_consequences: tuple[tuple[str, int], ...] = field(default=()) 

82 by_chromosome: tuple[tuple[str, int], ...] = field(default=()) 

83 positions: tuple[tuple[str, int, int, int, int], ...] = field(default=()) 

84 metadata: tuple[tuple[str, str], ...] = field(default=()) 

85 

86 @property 

87 def title(self) -> str: 

88 """Return the document title.""" 

89 return "Run summary" 

90 

91 @property 

92 def subtitle(self) -> str: 

93 """Return the headline counts.""" 

94 return f"{self.variants} variants, {self.alleles} alleles, {self.overlaps} overlaps" 

95 

96 def sections(self) -> tuple[ReportSection, ...]: 

97 """Return the summary as report sections, in the order the Perl summary shows them.""" 

98 return ( 

99 ReportSection( 

100 identifier="metadata", title="Run", headers=_METADATA_HEADERS, rows=tuple(self.metadata) 

101 ), 

102 ReportSection( 

103 identifier="classes", 

104 title="Variant classes", 

105 slices=tuple(Slice(label=name, value=count) for name, count in self.variant_classes), 

106 chart=ChartKind.PIE, 

107 ), 

108 ReportSection( 

109 identifier="most_severe", 

110 title="Most severe consequences", 

111 slices=_term_slices(self.most_severe), 

112 chart=ChartKind.PIE, 

113 ), 

114 ReportSection( 

115 identifier="consequences", 

116 title="Consequences (all)", 

117 slices=_term_slices(self.consequences), 

118 chart=ChartKind.BARS, 

119 ), 

120 ReportSection( 

121 identifier="coding", 

122 title="Coding consequences", 

123 slices=_term_slices(self.coding_consequences), 

124 chart=ChartKind.BARS, 

125 ), 

126 ReportSection( 

127 identifier="chromosomes", 

128 title="Variants by chromosome", 

129 slices=tuple(Slice(label=name, value=count) for name, count in self.by_chromosome), 

130 chart=ChartKind.BARS, 

131 ), 

132 ReportSection( 

133 identifier="positions", 

134 title="Position in chromosome", 

135 headers=_POSITION_HEADERS, 

136 rows=tuple(self.positions), 

137 ), 

138 ) 

139 

140 

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

142class RunSummaryDelta: 

143 """Mergeable summary counts from one worker buffer. 

144 

145 Attributes: 

146 variants (int): Number of variants. 

147 alleles (int): Number of alleles. 

148 overlaps (int): Number of feature overlaps. 

149 classes (tuple[tuple[str, int], ...]): Counts by variant class. 

150 most_severe (tuple[tuple[str, int], ...]): Counts by most severe consequence. 

151 consequences (tuple[tuple[str, int], ...]): Counts by consequence term. 

152 chromosomes (tuple[tuple[str, int], ...]): Counts by sequence region. 

153 positions (tuple[tuple[str, int], ...]): Observed positions by sequence region. 

154 """ 

155 

156 variants: int = 0 

157 alleles: int = 0 

158 overlaps: int = 0 

159 classes: tuple[tuple[str, int], ...] = field(default=()) 

160 most_severe: tuple[tuple[str, int], ...] = field(default=()) 

161 consequences: tuple[tuple[str, int], ...] = field(default=()) 

162 chromosomes: tuple[tuple[str, int], ...] = field(default=()) 

163 positions: tuple[tuple[str, int], ...] = field(default=()) 

164 

165 

166@define(kw_only=True, auto_attribs=True) 

167class _StreamingPositionBins: 

168 """Bounded position distribution for one recurrent sequence region. 

169 

170 Reproject existing counts by bin midpoint when the observed span expands. This keeps the 

171 region's endpoints and total exact while bounding storage to ``POSITION_BINS`` counters. 

172 """ 

173 

174 low: int | None = None 

175 high: int | None = None 

176 counts: list[int] = field(factory=lambda: [0] * POSITION_BINS) 

177 

178 def add(self, positions: tuple[int, ...]) -> None: 

179 """Add exact positions to the current bounded distribution.""" 

180 if not positions: 180 ↛ 181line 180 didn't jump to line 181 because the condition on line 180 was never true

181 return 

182 

183 new_low = min(positions) if self.low is None else min(self.low, *positions) 

184 new_high = max(positions) if self.high is None else max(self.high, *positions) 

185 if self.low is not None and self.high is not None: 

186 self._resize(new_low, new_high) 

187 self.low = new_low 

188 self.high = new_high 

189 for position in positions: 

190 self.counts[self._index(position)] += 1 

191 

192 def rows(self, chromosome: str) -> tuple[tuple[str, int, int, int, int], ...]: 

193 """Return up to ten non-empty coordinate ranges for this distribution.""" 

194 assert self.low is not None 

195 assert self.high is not None 

196 width = self._width(self.low, self.high) 

197 span = self.high - self.low + 1 

198 bin_count = min(POSITION_BINS, (span + width - 1) // width) 

199 rows = [] 

200 for index, count in enumerate(self.counts[:bin_count]): 

201 bin_low = self.low + index * width 

202 rows.append((chromosome, index + 1, bin_low, min(self.high, bin_low + width - 1), count)) 

203 return tuple(rows) 

204 

205 def _resize(self, low: int, high: int) -> None: 

206 """Reproject retained counts if new positions expand the observed span.""" 

207 assert self.low is not None 

208 assert self.high is not None 

209 if low == self.low and high == self.high: 209 ↛ 210line 209 didn't jump to line 210 because the condition on line 209 was never true

210 return 

211 

212 old_low = self.low 

213 old_high = self.high 

214 old_width = self._width(old_low, old_high) 

215 old_counts = self.counts 

216 self.low = low 

217 self.high = high 

218 self.counts = [0] * POSITION_BINS 

219 for index, count in enumerate(old_counts): 

220 if not count: 

221 continue 

222 bin_low = old_low + index * old_width 

223 bin_high = min(old_high, bin_low + old_width - 1) 

224 midpoint = bin_low + (bin_high - bin_low) // 2 

225 self.counts[self._index(midpoint)] += count 

226 

227 def _index(self, position: int) -> int: 

228 """Return the bin index for a position in the current span.""" 

229 assert self.low is not None 

230 assert self.high is not None 

231 width = self._width(self.low, self.high) 

232 return min((position - self.low) // width, POSITION_BINS - 1) 

233 

234 @staticmethod 

235 def _width(low: int, high: int) -> int: 

236 """Return the integral width of one report bin.""" 

237 return max(1, (high - low + 1 + POSITION_BINS - 1) // POSITION_BINS) 

238 

239 

240@define(kw_only=True, auto_attribs=True) 

241class RunSummaryCollector: 

242 """Incremental collector for a ``RunSummary``. 

243 

244 Attributes: 

245 metadata (dict[str, str]): The run's own facts, written into the summary as given. 

246 """ 

247 

248 metadata: dict[str, str] = field(factory=dict) 

249 _variants: int = field(default=0, init=False) 

250 _alleles: int = field(default=0, init=False) 

251 _overlaps: int = field(default=0, init=False) 

252 _classes: dict[str, int] = field(factory=dict, init=False) 

253 _most_severe: dict[str, int] = field(factory=dict, init=False) 

254 _consequences: dict[str, int] = field(factory=dict, init=False) 

255 _by_chromosome: dict[str, int] = field(factory=dict, init=False) 

256 _positions: dict[str, list[int]] = field(factory=dict, init=False) 

257 _streaming_positions: dict[str, _StreamingPositionBins] = field(factory=dict, init=False) 

258 

259 def observe(self, variation: Variation) -> None: 

260 """Count one variation and everything hanging off it. 

261 

262 Args: 

263 variation (Variation): The variation, with its alleles' consequences already known -- 

264 whether assigned by an annotator or read back from a file. 

265 """ 

266 uploaded_locus = variation.uploaded_locus 

267 uploaded_name = uploaded_locus.seq_region_name if uploaded_locus is not None else None 

268 chromosome = uploaded_name or UNKNOWN_VALUE 

269 self._assert_not_ordered_region(chromosome) 

270 self._variants += 1 

271 self._by_chromosome[chromosome] = self._by_chromosome.get(chromosome, 0) + 1 

272 self._positions.setdefault(chromosome, []).append(variation.start) 

273 

274 class_term = variation.class_so_term 

275 class_name = class_term.value if class_term is not None else "unknown" 

276 self._classes[class_name] = self._classes.get(class_name, 0) + 1 

277 

278 most_severe = variation.most_severe_consequence 

279 if most_severe is not None: 

280 self._most_severe[most_severe.term] = self._most_severe.get(most_severe.term, 0) + 1 

281 

282 for allele in variation.variation_alleles: 

283 self._alleles += 1 

284 self._overlaps += len(allele.transcript_variation_alleles) 

285 for consequence in allele.overlap_consequences: 

286 self._consequences[consequence.term] = self._consequences.get(consequence.term, 0) + 1 

287 

288 def merge(self, delta: RunSummaryDelta) -> None: 

289 """Merge a worker-buffer summary delta.""" 

290 

291 for chromosome, _position in delta.positions: 

292 self._assert_not_ordered_region(chromosome) 

293 self._merge_counts(delta) 

294 for chromosome, position in delta.positions: 

295 self._positions.setdefault(chromosome, []).append(position) 

296 

297 def merge_ordered_delta(self, delta: RunSummaryDelta) -> None: 

298 """Merge one sequence-region worker delta in arbitrary source order. 

299 

300 Every position in a delta must belong to one sequence region. Deltas for 

301 a region may recur after other regions. A bounded histogram per region 

302 releases every raw position after merging. Expanding a region's observed 

303 span reprojects its existing counts by bin midpoint, so endpoints and 

304 totals stay exact while individual bin counts become an estimate. 

305 

306 Raises: 

307 ValueError: If a delta mixes sequence regions or the region has unordered positions. 

308 """ 

309 

310 regions = {chromosome for chromosome, _position in delta.positions} 

311 if not regions: 311 ↛ 312line 311 didn't jump to line 312 because the condition on line 311 was never true

312 self._merge_counts(delta) 

313 return 

314 if len(regions) != 1: 

315 raise ValueError("an ordered summary delta must contain one sequence region") 

316 

317 region = next(iter(regions)) 

318 if region in self._positions: 318 ↛ 319line 318 didn't jump to line 319 because the condition on line 318 was never true

319 raise ValueError(f"ordered summary region {region!r} already has unordered positions") 

320 self._merge_counts(delta) 

321 positions = tuple(position for _chromosome, position in delta.positions) 

322 self._streaming_positions.setdefault(region, _StreamingPositionBins()).add(positions) 

323 

324 @property 

325 def completed_position_regions(self) -> tuple[str, ...]: 

326 """Return regions whose raw positions have been released into bounded bins.""" 

327 

328 return tuple(sorted(self._streaming_positions)) 

329 

330 @property 

331 def retained_ordered_position_count(self) -> int: 

332 """Return the number of raw positions retained by streaming merges.""" 

333 

334 return 0 

335 

336 def _merge_counts(self, delta: RunSummaryDelta) -> None: 

337 """Merge non-positional counts from a worker delta.""" 

338 

339 self._variants += delta.variants 

340 self._alleles += delta.alleles 

341 self._overlaps += delta.overlaps 

342 for totals, values in ( 

343 (self._classes, delta.classes), 

344 (self._most_severe, delta.most_severe), 

345 (self._consequences, delta.consequences), 

346 (self._by_chromosome, delta.chromosomes), 

347 ): 

348 for name, count in values: 

349 totals[name] = totals.get(name, 0) + count 

350 

351 def delta(self) -> RunSummaryDelta: 

352 """Return the mergeable counts accumulated so far.""" 

353 positions: list[tuple[str, int]] = [] 

354 for chromosome, values in self._positions.items(): 

355 for position in values: 

356 positions.append((chromosome, position)) 

357 return RunSummaryDelta( 

358 variants=self._variants, 

359 alleles=self._alleles, 

360 overlaps=self._overlaps, 

361 classes=tuple(self._classes.items()), 

362 most_severe=tuple(self._most_severe.items()), 

363 consequences=tuple(self._consequences.items()), 

364 chromosomes=tuple(self._by_chromosome.items()), 

365 positions=tuple(positions), 

366 ) 

367 

368 def finish(self) -> RunSummary: 

369 """Return the summary of everything observed so far.""" 

370 coding = coding_terms() 

371 consequences = _counts(self._consequences) 

372 return RunSummary( 

373 variants=self._variants, 

374 alleles=self._alleles, 

375 overlaps=self._overlaps, 

376 variant_classes=_counts(self._classes), 

377 most_severe=_counts(self._most_severe), 

378 consequences=consequences, 

379 coding_consequences=tuple((term, count) for term, count in consequences if term in coding), 

380 by_chromosome=_counts(self._by_chromosome), 

381 positions=self._all_binned_positions(), 

382 metadata=tuple(self.metadata.items()), 

383 ) 

384 

385 def _binned_positions(self) -> tuple[tuple[str, int, int, int, int], ...]: 

386 """Return each chromosome's variants binned along its observed span.""" 

387 rows: list[tuple[str, int, int, int, int]] = [] 

388 for chromosome in sorted(self._positions): 

389 positions = self._positions[chromosome] 

390 distribution = _StreamingPositionBins() 

391 distribution.add(tuple(positions)) 

392 rows.extend(distribution.rows(chromosome)) 

393 return tuple(rows) 

394 

395 def _all_binned_positions(self) -> tuple[tuple[str, int, int, int, int], ...]: 

396 """Return unordered and streaming position rows in report order.""" 

397 

398 rows = list(self._binned_positions()) 

399 for chromosome, distribution in self._streaming_positions.items(): 

400 rows.extend(distribution.rows(chromosome)) 

401 return tuple(sorted(rows, key=lambda row: (row[0], row[1]))) 

402 

403 def _assert_not_ordered_region(self, chromosome: str) -> None: 

404 """Reject unordered positions that would invalidate streaming bins.""" 

405 

406 if chromosome in self._streaming_positions: 406 ↛ 407line 406 didn't jump to line 407 because the condition on line 406 was never true

407 raise ValueError(f"summary region {chromosome!r} is already managed by ordered deltas")