Coverage for src/python/ensembl/vep/trace/run.py: 100%

97 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"""Run-level aggregation of annotation traces. 

15 

16``AnnotationTrace`` describes one overlap. ``RunTrace`` aggregates fact use, charged and avoided 

17costs, reached cost tiers, and emitted terms across a run. It remains separate from the lightweight 

18term-level ``RunSummary`` because fact-level tracing is optional and more expensive. 

19""" 

20 

21from __future__ import annotations 

22 

23from collections.abc import Iterable 

24 

25from attrs import define, field, frozen 

26 

27from ensembl.vep.common import CostTier 

28from ensembl.vep.render.chart import Slice 

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

30from ensembl.vep.trace.annotation import AnnotationTrace 

31from ensembl.vep.trace.events import FactOrigin 

32 

33__all__ = ["FACT_HEADERS", "FactUsage", "RunTrace"] 

34 

35FACT_HEADERS = ("Fact", "Computed", "Prefilled", "Cached", "Forced False", "Reads", "Cost", "Avoided") 

36"""Column headers matching ``RunTrace.fact_rows``.""" 

37 

38 

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

40class FactUsage: 

41 """Aggregate one fact's use across a run. 

42 

43 Attributes: 

44 name (str): The fact's name. 

45 computed (int): Overlaps that computed the fact. 

46 prefilled (int): Overlaps supplied by a zone map. 

47 cached (int): Overlaps supplied by the codon cache. 

48 forced_false (int): Overlaps that proved the fact false without computation. 

49 reads (int): Total ``get_fact`` requests. 

50 charged_cost (int): Total declared cost charged. 

51 avoided_cost (int): Total declared cost avoided. 

52 """ 

53 

54 name: str 

55 computed: int = field(default=0) 

56 prefilled: int = field(default=0) 

57 cached: int = field(default=0) 

58 forced_false: int = field(default=0) 

59 reads: int = field(default=0) 

60 charged_cost: int = field(default=0) 

61 avoided_cost: int = field(default=0) 

62 

63 @property 

64 def touched(self) -> int: 

65 """Return the number of overlaps that used this fact.""" 

66 return self.computed + self.prefilled + self.cached + self.forced_false 

67 

68 

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

70class _FactUsageBuilder: 

71 """Accumulate one fact's usage during a fold, then freeze it to a ``FactUsage``.""" 

72 

73 name: str 

74 computed: int = field(default=0) 

75 prefilled: int = field(default=0) 

76 cached: int = field(default=0) 

77 forced_false: int = field(default=0) 

78 reads: int = field(default=0) 

79 charged_cost: int = field(default=0) 

80 avoided_cost: int = field(default=0) 

81 declared_cost: int = field(default=0) 

82 

83 def freeze(self) -> FactUsage: 

84 """Return the accumulated totals as a ``FactUsage``.""" 

85 return FactUsage( 

86 name=self.name, 

87 computed=self.computed, 

88 prefilled=self.prefilled, 

89 cached=self.cached, 

90 forced_false=self.forced_false, 

91 reads=self.reads, 

92 charged_cost=self.charged_cost, 

93 avoided_cost=self.avoided_cost, 

94 ) 

95 

96 

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

98class RunTrace: 

99 """Record fact-level totals for an annotation run. 

100 

101 Attributes: 

102 overlaps (int): Number of traced overlaps. 

103 fact_usage (tuple[FactUsage, ...]): Per-fact totals ordered by charged cost. 

104 term_counts (tuple[tuple[str, int], ...]): Emitted-term counts ordered by frequency. 

105 tier_reach (tuple[tuple[str, int], ...]): Computed-fact counts by cost tier. 

106 charged_cost (int): Total declared cost charged. 

107 avoided_cost (int): Total declared cost avoided. 

108 annotator_name (str): Annotator represented by the trace. 

109 cost_table (str): Cost table used for declared fact costs. 

110 """ 

111 

112 overlaps: int = field(default=0) 

113 fact_usage: tuple[FactUsage, ...] = field(default=()) 

114 term_counts: tuple[tuple[str, int], ...] = field(default=()) 

115 tier_reach: tuple[tuple[str, int], ...] = field(default=()) 

116 charged_cost: int = field(default=0) 

117 avoided_cost: int = field(default=0) 

118 annotator_name: str = field(default="") 

119 cost_table: str = field(default="") 

120 

121 @property 

122 def title(self) -> str: 

123 """Return the report title.""" 

124 return f"Fact profile: {self.annotator_name}" if self.annotator_name else "Fact profile" 

125 

126 @property 

127 def subtitle(self) -> str: 

128 """Return the report totals and cost-table description.""" 

129 table = f"; costs from {self.cost_table}" if self.cost_table else "" 

130 return ( 

131 f"{self.overlaps} overlaps, cost {self.charged_cost} charged, " 

132 f"{self.avoided_cost} avoided{table}" 

133 ) 

134 

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

136 """Return the profile as report sections.""" 

137 return ( 

138 ReportSection( 

139 identifier="facts", title="Facts", headers=FACT_HEADERS, rows=tuple(self.fact_rows()) 

140 ), 

141 ReportSection( 

142 identifier="tiers", 

143 title="Facts computed, by cost tier", 

144 slices=tuple(Slice(label=label, value=count) for label, count in self.tier_reach), 

145 chart=ChartKind.BARS, 

146 ), 

147 ReportSection( 

148 identifier="terms", 

149 title="Emitted terms", 

150 slices=tuple(Slice(label=term, value=count) for term, count in self.term_counts), 

151 chart=ChartKind.BARS, 

152 ), 

153 ) 

154 

155 @classmethod 

156 def fold( 

157 cls, traces: Iterable[AnnotationTrace], *, annotator_name: str = "", cost_table: str = "" 

158 ) -> RunTrace: 

159 """Build run-level totals from per-overlap traces. 

160 

161 Args: 

162 traces (Iterable[AnnotationTrace]): Derivations to aggregate. 

163 annotator_name (str): Annotator that produced the traces. 

164 cost_table (str): Cost table used for declared fact costs. 

165 

166 Returns: 

167 RunTrace: Aggregated run trace. 

168 """ 

169 builders: dict[str, _FactUsageBuilder] = {} 

170 term_totals: dict[str, int] = {} 

171 overlaps = 0 

172 

173 for trace in traces: 

174 overlaps += 1 

175 for term in trace.emitted_terms: 

176 term_totals[term] = term_totals.get(term, 0) + 1 

177 for event in trace.fact_events: 

178 builder = builders.get(event.name) 

179 if builder is None: 

180 builder = _FactUsageBuilder(name=event.name) 

181 builders[event.name] = builder 

182 builder.reads += event.reads 

183 if event.origin is FactOrigin.COMPUTED: 

184 builder.computed += 1 

185 builder.charged_cost += event.cost 

186 builder.declared_cost = max(builder.declared_cost, event.cost) 

187 elif event.origin is FactOrigin.PREFILLED: 

188 builder.prefilled += 1 

189 elif event.origin is FactOrigin.CACHED: 

190 builder.cached += 1 

191 else: 

192 builder.forced_false += 1 

193 builder.avoided_cost += event.cost 

194 builder.declared_cost = max(builder.declared_cost, event.cost) 

195 

196 usage = [builder.freeze() for builder in builders.values()] 

197 usage.sort(key=lambda entry: (-entry.charged_cost, entry.name)) 

198 

199 tier_totals: dict[str, int] = {} 

200 for builder in builders.values(): 

201 if builder.computed: 

202 label = CostTier.label(builder.declared_cost) 

203 tier_totals[label] = tier_totals.get(label, 0) + builder.computed 

204 

205 terms = sorted(term_totals.items(), key=lambda entry: (-entry[1], entry[0])) 

206 tiers = sorted(tier_totals.items(), key=lambda entry: (-entry[1], entry[0])) 

207 return cls( 

208 overlaps=overlaps, 

209 fact_usage=tuple(usage), 

210 term_counts=tuple(terms), 

211 tier_reach=tuple(tiers), 

212 charged_cost=sum(entry.charged_cost for entry in usage), 

213 avoided_cost=sum(entry.avoided_cost for entry in usage), 

214 annotator_name=annotator_name, 

215 cost_table=cost_table, 

216 ) 

217 

218 def fact_rows(self) -> list[tuple[object, ...]]: 

219 """Return the per-fact totals as table rows, in ``FACT_HEADERS`` order.""" 

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

221 for usage in self.fact_usage: 

222 rows.append( 

223 ( 

224 usage.name, 

225 usage.computed, 

226 usage.prefilled, 

227 usage.cached, 

228 usage.forced_false, 

229 usage.reads, 

230 usage.charged_cost, 

231 usage.avoided_cost, 

232 ) 

233 ) 

234 return rows