Coverage for src/python/ensembl/vep/annotators/consequence/facts/costs.py: 98%

69 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"""Measure fact evaluation costs. 

15 

16Declared tiers provide relative ordering rather than wall-clock timings. Profiling measures each 

17fact's self-time and normalises it to the ``BOUNDS = 1`` scale used by declared costs. 

18 

19Profiling temporarily replaces registered compute functions with timing wrappers and therefore 

20belongs only in explicit measurement runs. 

21""" 

22 

23from __future__ import annotations 

24 

25import json 

26import statistics 

27import time 

28from collections.abc import Callable 

29from importlib.resources import files 

30from pathlib import Path 

31 

32from attrs import evolve 

33 

34from ensembl.vep.common import CostTier 

35from ensembl.vep.annotators.consequence.context.fact import FactContext 

36from ensembl.vep.annotators.consequence.facts.base import ( 

37 FACT_COST_OVERRIDE_RESOURCE, 

38 Fact, 

39 REGISTRY, 

40 get_fact, 

41) 

42 

43__all__ = [ 

44 "declared_vs_measured", 

45 "fact_costs_path", 

46 "normalised_cost_table", 

47 "profile_self_nanoseconds", 

48 "write_cost_table", 

49] 

50 

51 

52def profile_self_nanoseconds(fact_contexts: list[FactContext]) -> dict[str, float]: 

53 """Profile every registered fact's mean self-time, in nanoseconds, over ``fact_contexts``. 

54 

55 Temporarily wraps every Fact in REGISTRY with a timing shim (restored in a 

56 ``finally`` block, so a failure partway through still leaves the registry as it found it), then 

57 computes every fact for every context. 

58 

59 Args: 

60 fact_contexts (list[FactContext]): Contexts to compute every fact over. Each is reset 

61 first. 

62 

63 Returns: 

64 dict[str, float]: Fact name -> mean self-time in nanoseconds, over every context in which 

65 that fact was computed (every fact is computed for every context here, so the divisor 

66 is ``len(fact_contexts)`` for all of them). 

67 """ 

68 self_nanoseconds_total: dict[str, float] = {} 

69 computation_counts: dict[str, int] = {} 

70 nested_time_stack: list[float] = [] 

71 original_compute_functions = {name: registered_fact.compute for name, registered_fact in REGISTRY.items()} 

72 

73 def make_timed_compute( 

74 fact_name: str, original_compute: Callable[[FactContext], object] 

75 ) -> Callable[[FactContext], object]: 

76 def timed_compute(fact_context: FactContext) -> object: 

77 nested_time_stack.append(0.0) 

78 started_at = time.perf_counter_ns() 

79 value = original_compute(fact_context) 

80 total_elapsed_nanoseconds = time.perf_counter_ns() - started_at 

81 nested_elapsed_nanoseconds = nested_time_stack.pop() 

82 self_elapsed_nanoseconds = total_elapsed_nanoseconds - nested_elapsed_nanoseconds 

83 if nested_time_stack: 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true

84 nested_time_stack[-1] += total_elapsed_nanoseconds 

85 self_nanoseconds_total[fact_name] = ( 

86 self_nanoseconds_total.get(fact_name, 0.0) + self_elapsed_nanoseconds 

87 ) 

88 computation_counts[fact_name] = computation_counts.get(fact_name, 0) + 1 

89 return value 

90 

91 return timed_compute 

92 

93 try: 

94 for fact_name, registered_fact in list(REGISTRY.items()): 

95 REGISTRY[fact_name] = _with_compute( 

96 registered_fact, make_timed_compute(fact_name, registered_fact.compute) 

97 ) 

98 

99 fact_names = list(REGISTRY) 

100 for fact_context in fact_contexts: 

101 fact_context.reset() 

102 for fact_name in fact_names: 

103 get_fact(fact_context, fact_name) 

104 finally: 

105 for fact_name, original_compute in original_compute_functions.items(): 

106 REGISTRY[fact_name] = _with_compute(REGISTRY[fact_name], original_compute) 

107 

108 return { 

109 fact_name: total_nanoseconds / computation_counts[fact_name] 

110 for fact_name, total_nanoseconds in self_nanoseconds_total.items() 

111 } 

112 

113 

114def _with_compute(registered_fact: Fact, compute: Callable[[FactContext], object]) -> Fact: 

115 """Return a copy of ``registered_fact`` with its ``compute`` replaced. 

116 

117 A tiny local helper rather than importing ``attrs.evolve`` at call sites throughout 

118 profile_self_nanoseconds, since Fact is frozen. 

119 

120 Args: 

121 registered_fact (Fact): The fact to copy. 

122 compute (Callable[[FactContext], object]): The replacement ``compute`` callable. 

123 

124 Returns: 

125 Fact: The copy, with every other field unchanged. 

126 """ 

127 return evolve(registered_fact, compute=compute) 

128 

129 

130def normalised_cost_table(measured_self_nanoseconds: dict[str, float]) -> dict[str, int]: 

131 """Normalise every fact's measured self-time to BOUNDS = 1 and write it to ``output_path``. 

132 

133 The inverse of ``apply_fact_cost_overrides``: BOUNDS = 1 is the same normalisation the declared 

134 tier constants use, so a measured table is interchangeable with the declared ones. 

135 

136 Args: 

137 measured_self_nanoseconds (dict[str, float]): Fact name -> mean self-time in nanoseconds. 

138 

139 Returns: 

140 dict[str, int]: Fact name -> cost in BOUNDS units. 

141 

142 Raises: 

143 RuntimeError: If no BOUNDS-tier fact was measured, leaving nothing to normalise against. 

144 """ 

145 bounds_facts = [name for name in measured_self_nanoseconds if REGISTRY[name].cost == CostTier.BOUNDS] 

146 if not bounds_facts: 

147 raise RuntimeError("no BOUNDS-tier fact was measured; cannot normalise -- widen the corpus") 

148 bounds_mean_nanoseconds = statistics.mean(measured_self_nanoseconds[name] for name in bounds_facts) 

149 

150 cost_table = {} 

151 for fact_name, self_nanoseconds in measured_self_nanoseconds.items(): 

152 cost_table[fact_name] = max(0, round(self_nanoseconds / bounds_mean_nanoseconds)) 

153 return cost_table 

154 

155 

156def fact_costs_path() -> Path: 

157 """Return the filesystem path of the packaged measured-cost table. 

158 

159 Resolved the same way ``load_fact_cost_overrides_from_package`` reads it, so ``--write`` and 

160 the loader can no longer disagree about where the table lives. 

161 """ 

162 resource = files("ensembl.vep.annotators.consequence").joinpath(FACT_COST_OVERRIDE_RESOURCE) 

163 return Path(str(resource)) 

164 

165 

166def write_cost_table(cost_table: dict[str, int], output_path: Path | None = None) -> Path: 

167 """Write a measured cost table as JSON, and return where it was written. 

168 

169 Args: 

170 cost_table (dict[str, int]): Fact name -> cost in BOUNDS units. 

171 output_path (Path | None): Where to write, or None for the packaged table. 

172 

173 Returns: 

174 Path: The path written to. 

175 """ 

176 destination = output_path or fact_costs_path() 

177 destination.parent.mkdir(parents=True, exist_ok=True) 

178 destination.write_text(json.dumps(cost_table, indent=2, sort_keys=True) + "\n", encoding="utf-8") 

179 return destination 

180 

181 

182def declared_vs_measured(measured_self_nanoseconds: dict[str, float]) -> list[tuple[str, str, float, int]]: 

183 """Return one row per fact comparing its declared tier against what was measured. 

184 

185 Returns: 

186 ``(fact name, declared tier label, measured ns, measured cost in BOUNDS units)``, 

187 ordered by declared cost then name. 

188 """ 

189 cost_table = normalised_cost_table(measured_self_nanoseconds) 

190 rows = [] 

191 for fact_name, self_nanoseconds in measured_self_nanoseconds.items(): 

192 declared = REGISTRY[fact_name].cost 

193 rows.append((fact_name, CostTier.label(declared), self_nanoseconds, cost_table[fact_name])) 

194 rows.sort(key=lambda row: (REGISTRY[row[0]].cost, row[0])) 

195 return rows