Coverage for src/python/ensembl/vep/trace/reconstruct.py: 97%

85 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"""Reconstruct annotation traces from completed fact evaluation. 

15 

16The fact memo, rule set, and fired terms provide most of a derivation after annotation. Live 

17recording retains only read counts, cache origins, and the partial assignment used by staged 

18annotation because those values cannot be recovered by replay. 

19 

20Fact origins are reconstructed as follows: 

21 

22* **computed** -- in the memo, and no cache claimed it. 

23* **prefilled / cached** -- in the memo, and the recorder says which cache put it there. 

24* **forced False** -- False in the staged assignment and absent from the memo, so it was proved 

25 False by ``requires`` propagation without being computed. 

26 

27Call ``memo_fact_events`` before reconstructing rules. Rule reconstruction reads facts again, so 

28capturing read counts afterwards would include replay activity. 

29""" 

30 

31from __future__ import annotations 

32 

33from collections.abc import Mapping, Sequence 

34 

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

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

37from ensembl.vep.annotators.consequence.rules.expressions import And, Atom, Expr, Not, Or 

38from ensembl.vep.annotators.consequence.rules.rulesets import FactRule 

39from ensembl.vep.trace.events import FactEvent, FactOrigin, PruneEvent, RuleEvent 

40 

41__all__ = [ 

42 "explain_partial_settlement", 

43 "forced_false_events", 

44 "guarded_rule_events", 

45 "memo_fact_events", 

46 "partial_rule_events", 

47 "plain_rule_events", 

48 "subsumption_events", 

49] 

50 

51 

52def memo_fact_events(fact_context: FactContext) -> tuple[FactEvent, ...]: 

53 """Return memoised facts in materialisation order. 

54 

55 Dictionary insertion order records when each fact first entered the memo. 

56 

57 Args: 

58 fact_context (FactContext): Evaluated context containing the memo and optional recorder. 

59 

60 Returns: 

61 tuple[FactEvent, ...]: Fact events in materialisation order. 

62 """ 

63 recorder = fact_context.recorder 

64 read_counts = recorder.read_counts if recorder is not None else {} 

65 served = recorder.served if recorder is not None else {} 

66 

67 events = [] 

68 for name, value in fact_context.memo.items(): 

69 origin = served.get(name, FactOrigin.COMPUTED) 

70 registered_fact = REGISTRY.get(name) 

71 cost = registered_fact.cost if registered_fact is not None else 0 

72 events.append( 

73 FactEvent( 

74 name=name, 

75 value=value, 

76 cost=cost if origin is FactOrigin.COMPUTED else 0, 

77 origin=origin, 

78 reads=read_counts.get(name, 0), 

79 ) 

80 ) 

81 return tuple(events) 

82 

83 

84def forced_false_events(known: Mapping[str, bool], memo: Mapping[str, object]) -> tuple[FactEvent, ...]: 

85 """Return facts proved false through ``requires`` propagation. 

86 

87 A false value in the closed partial assignment that is absent from the memo was settled 

88 without computation. 

89 

90 Args: 

91 known (Mapping[str, bool]): Partial assignment used for rule evaluation. 

92 memo (Mapping[str, object]): Completed fact memo. 

93 

94 Returns: 

95 tuple[FactEvent, ...]: Forced-false events with avoided cost and forcing atoms. 

96 """ 

97 events = [] 

98 for name, value in known.items(): 

99 if value is not False or name in memo: 

100 continue 

101 registered_fact = REGISTRY.get(name) 

102 if registered_fact is None: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true

103 continue 

104 forced_by = tuple(required for required in registered_fact.requires if known.get(required) is False) 

105 events.append( 

106 FactEvent( 

107 name=name, 

108 value=False, 

109 cost=registered_fact.cost, 

110 origin=FactOrigin.FORCED_FALSE, 

111 forced_by=forced_by, 

112 ) 

113 ) 

114 return tuple(events) 

115 

116 

117# pylint: disable-next=too-many-return-statements 

118def explain_partial_settlement(expr: Expr, known: dict[str, bool]) -> list[tuple[str, bool]]: 

119 """Return atom-value pairs that settled a partial expression. 

120 

121 This follows ``Expr.evaluate_partial`` short-circuiting until it reaches the false conjunct or 

122 true disjunct that determined the result. 

123 

124 Args: 

125 expr (Expr): Expression already settled by partial evaluation. 

126 known (dict[str, bool]): Partial assignment that settled the expression. 

127 

128 Returns: 

129 list[tuple[str, bool]]: Settling atoms in evaluation order, or an empty list. 

130 """ 

131 if isinstance(expr, Atom): 

132 value = known.get(expr.name) 

133 return [(expr.name, value)] if value is not None else [] 

134 if isinstance(expr, Not): 

135 return explain_partial_settlement(expr.child, known) 

136 if isinstance(expr, And): 

137 for child in expr.children: 

138 if child.evaluate_partial(known) is False: 

139 return explain_partial_settlement(child, known) 

140 return [] 

141 if isinstance(expr, Or): 141 ↛ 146line 141 didn't jump to line 146 because the condition on line 141 was always true

142 for child in expr.children: 

143 if child.evaluate_partial(known) is True: 

144 return explain_partial_settlement(child, known) 

145 return [] 

146 return [] 

147 

148 

149def plain_rule_events(rules: Sequence[FactRule], hit_terms: Sequence[str]) -> tuple[RuleEvent, ...]: 

150 """Return rule events for fully evaluated formulas. 

151 

152 Use this for strategies without staging or a cheap-guard prefilter. 

153 

154 Args: 

155 rules (Sequence[FactRule]): Rules considered, in rank order. 

156 hit_terms (Sequence[str]): Terms whose rules evaluated true. 

157 

158 Returns: 

159 tuple[RuleEvent, ...]: Rule events in rank order. 

160 """ 

161 hit_terms_set = set(hit_terms) 

162 events = [] 

163 for rule in rules: 

164 events.append( 

165 RuleEvent( 

166 term=rule.term, 

167 rank=rule.rank, 

168 fired=rule.term in hit_terms_set, 

169 settled_early=False, 

170 reason=repr(rule.when), 

171 ) 

172 ) 

173 return tuple(events) 

174 

175 

176def guarded_rule_events( 

177 rules: Sequence[FactRule], 

178 candidate_terms: set[str], 

179 hit_terms: Sequence[str], 

180 guard_flags: Mapping[str, bool], 

181) -> tuple[RuleEvent, ...]: 

182 """Return rule events that distinguish guard rejection from full evaluation. 

183 

184 A rule outside ``candidate_terms`` was rejected by ``FactRule.cheap_guard`` and therefore 

185 reports failed guard atoms instead of its unevaluated formula. 

186 

187 Args: 

188 rules (Sequence[FactRule]): Rules in rank order. 

189 candidate_terms (set[str]): Terms whose rules passed the guard. 

190 hit_terms (Sequence[str]): Candidate terms whose rules evaluated true. 

191 guard_flags (Mapping[str, bool]): Guard values for the overlap. 

192 

193 Returns: 

194 tuple[RuleEvent, ...]: Rule events in rank order. 

195 """ 

196 hit_terms_set = set(hit_terms) 

197 events = [] 

198 for rule in rules: 

199 if rule.term in candidate_terms: 

200 events.append( 

201 RuleEvent( 

202 term=rule.term, 

203 rank=rule.rank, 

204 fired=rule.term in hit_terms_set, 

205 settled_early=False, 

206 reason=repr(rule.when), 

207 ) 

208 ) 

209 continue 

210 failed_atoms = sorted(atom for atom in rule.cheap_guard() if not guard_flags.get(atom, False)) 

211 reason = ( 

212 "guard failed: " + ", ".join(f"{atom}=False" for atom in failed_atoms) 

213 if failed_atoms 

214 else "guard failed" 

215 ) 

216 events.append( 

217 RuleEvent(term=rule.term, rank=rule.rank, fired=False, settled_early=True, reason=reason) 

218 ) 

219 return tuple(events) 

220 

221 

222def partial_rule_events( 

223 rules: Sequence[FactRule], known: dict[str, bool], hit_terms: Sequence[str] 

224) -> tuple[RuleEvent, ...]: 

225 """Return rule events from partial and complete verdicts. 

226 

227 Rules settled by ``known`` report the determining atoms. Other rules report that they required 

228 full evaluation. 

229 

230 Args: 

231 rules (Sequence[FactRule]): Rules in rank order. 

232 known (dict[str, bool]): Partial assignment used by staged evaluation. 

233 hit_terms (Sequence[str]): Terms whose complete verdict was true. 

234 

235 Returns: 

236 tuple[RuleEvent, ...]: Rule events in rank order. 

237 """ 

238 hit_terms_set = set(hit_terms) 

239 events = [] 

240 for rule in rules: 

241 verdict = rule.when.evaluate_partial(known) 

242 fired = rule.term in hit_terms_set 

243 if verdict is None: 

244 events.append( 

245 RuleEvent( 

246 term=rule.term, 

247 rank=rule.rank, 

248 fired=fired, 

249 settled_early=False, 

250 reason="fell through to full evaluation (needed expensive tier)", 

251 ) 

252 ) 

253 continue 

254 settling_atoms = explain_partial_settlement(rule.when, known) 

255 reason = ( 

256 "settled early: " + ", ".join(f"{name}={value}" for name, value in settling_atoms) 

257 if settling_atoms 

258 else f"settled early: {rule.when!r}" 

259 ) 

260 events.append( 

261 RuleEvent(term=rule.term, rank=rule.rank, fired=fired, settled_early=True, reason=reason) 

262 ) 

263 return tuple(events) 

264 

265 

266def subsumption_events(by_term: Mapping[str, FactRule], hit_terms: Sequence[str]) -> tuple[PruneEvent, ...]: 

267 """Return the pruning decisions made by ``rules.rulesets.prune``. 

268 

269 This read-only replay avoids adding trace state to the pruning path. 

270 

271 Args: 

272 by_term (Mapping[str, FactRule]): Rules indexed by term. 

273 hit_terms (Sequence[str]): Terms whose rules fired before pruning. 

274 

275 Returns: 

276 tuple[PruneEvent, ...]: Pruning events for dropped terms. 

277 """ 

278 hit_terms_set = set(hit_terms) 

279 events = [] 

280 for term in hit_terms: 

281 for subsumed_term in by_term[term].subsumes: 

282 if subsumed_term in hit_terms_set: 

283 events.append(PruneEvent(dropped_term=subsumed_term, subsumed_by=term)) 

284 return tuple(events)