Coverage for src/python/ensembl/vep/annotators/consequence/rules/expressions.py: 100%

98 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"""Boolean expression tree for consequence rules.""" 

15 

16from __future__ import annotations 

17 

18from typing import TYPE_CHECKING 

19 

20from attrs import field, frozen 

21 

22from ensembl.vep.annotators.consequence.facts.base import get_fact, total_cost 

23 

24if TYPE_CHECKING: 

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

26 

27__all__ = ["And", "Atom", "Expr", "Not", "Or", "all_of", "any_of", "expr_from_json", "no"] 

28 

29 

30class Expr: 

31 """Represent a Boolean expression over fact atoms.""" 

32 

33 def atoms(self) -> set[str]: 

34 """Return every fact atom referenced by this expression. 

35 

36 Returns: 

37 set[str]: The referenced fact atom names. 

38 """ 

39 raise NotImplementedError 

40 

41 def evaluate(self, fact_context: FactContext) -> bool: 

42 """Evaluate this expression against a fact context, computing facts as needed. 

43 

44 Args: 

45 fact_context (FactContext): The overlap to evaluate against. 

46 

47 Returns: 

48 bool: The expression's truth value. 

49 """ 

50 raise NotImplementedError 

51 

52 def cost(self) -> int: 

53 """Return the cold cost of evaluating this expression. 

54 

55 Returns: 

56 int: The total cost of every atom referenced, counting each shared dependency once. 

57 """ 

58 return total_cost(self.atoms()) 

59 

60 def evaluate_partial(self, known: dict[str, bool]) -> bool | None: 

61 """Evaluate this expression against a partial (Kleene) assignment. 

62 

63 Returns True/False when the atoms in ``known`` already settle the formula, and None when 

64 they do not. This is what lets an annotator decide a rule from cheap facts alone and 

65 never touch the expensive tiers. 

66 

67 Args: 

68 known (dict[str, bool]): A partial assignment of fact atom names to boolean values. 

69 

70 Returns: 

71 bool | None: The expression's truth value if settled by ``known``, else None. 

72 """ 

73 raise NotImplementedError 

74 

75 def __and__(self, other: Expr) -> Expr: 

76 return And(self, other) 

77 

78 def __or__(self, other: Expr) -> Expr: 

79 return Or(self, other) 

80 

81 def __invert__(self) -> Expr: 

82 return Not(child=self) 

83 

84 

85@frozen(kw_only=False, auto_attribs=True) 

86class Atom(Expr): 

87 """Represent one fact atom by name.""" 

88 

89 name: str 

90 

91 def atoms(self) -> set[str]: 

92 """Return this atom's name.""" 

93 return {self.name} 

94 

95 def evaluate(self, fact_context: FactContext) -> bool: 

96 """Return this atom's value in a fact context.""" 

97 return bool(get_fact(fact_context, self.name)) 

98 

99 def evaluate_partial(self, known: dict[str, bool]) -> bool | None: 

100 """Return this atom's known value, if assigned.""" 

101 return known.get(self.name) 

102 

103 def __repr__(self) -> str: 

104 return self.name 

105 

106 

107@frozen(kw_only=False, auto_attribs=True) 

108class Not(Expr): 

109 """Negate one child expression.""" 

110 

111 child: Expr 

112 

113 def atoms(self) -> set[str]: 

114 """Return the atoms referenced by the child expression.""" 

115 return self.child.atoms() 

116 

117 def evaluate(self, fact_context: FactContext) -> bool: 

118 """Return the negated child value in a fact context.""" 

119 return not self.child.evaluate(fact_context) 

120 

121 def evaluate_partial(self, known: dict[str, bool]) -> bool | None: 

122 """Return the negated child value when it is known.""" 

123 value = self.child.evaluate_partial(known) 

124 return None if value is None else not value 

125 

126 def __repr__(self) -> str: 

127 return f"!{self.child!r}" 

128 

129 

130@frozen(kw_only=False, auto_attribs=True, init=False) 

131class And(Expr): 

132 """Combine child expressions with logical conjunction.""" 

133 

134 children: tuple[Expr, ...] = field() 

135 

136 def __init__(self, *children: Expr) -> None: 

137 object.__setattr__(self, "children", tuple(children)) 

138 

139 def atoms(self) -> set[str]: 

140 """Return the atoms referenced by all child expressions.""" 

141 return set().union(*(child.atoms() for child in self.children)) if self.children else set() 

142 

143 def evaluate(self, fact_context: FactContext) -> bool: 

144 """Return whether every child is true in a fact context.""" 

145 # Cheapest conjunct first: a false cheap test skips the expensive ones. 

146 # TBD: check by cost() or closure cost()? The latter is more expensive to compute but 

147 # should be more accurate. 

148 for child in sorted(self.children, key=lambda child: child.cost()): 

149 if not child.evaluate(fact_context): 

150 return False 

151 return True 

152 

153 def evaluate_partial(self, known: dict[str, bool]) -> bool | None: 

154 """Return the conjunction when the known values settle it.""" 

155 unknown = False 

156 for child in self.children: 

157 value = child.evaluate_partial(known) 

158 if value is False: 

159 return False 

160 if value is None: 

161 unknown = True 

162 return None if unknown else True 

163 

164 def __repr__(self) -> str: 

165 return "(" + " & ".join(repr(child) for child in self.children) + ")" 

166 

167 

168@frozen(kw_only=False, auto_attribs=True, init=False) 

169class Or(Expr): 

170 """Combine child expressions with logical disjunction.""" 

171 

172 children: tuple[Expr, ...] = field() 

173 

174 def __init__(self, *children: Expr) -> None: 

175 object.__setattr__(self, "children", tuple(children)) 

176 

177 def atoms(self) -> set[str]: 

178 """Return the atoms referenced by all child expressions.""" 

179 return set().union(*(child.atoms() for child in self.children)) if self.children else set() 

180 

181 def evaluate(self, fact_context: FactContext) -> bool: 

182 """Return whether any child is true in a fact context.""" 

183 for child in sorted(self.children, key=lambda child: child.cost()): 

184 if child.evaluate(fact_context): 

185 return True 

186 return False 

187 

188 def evaluate_partial(self, known: dict[str, bool]) -> bool | None: 

189 """Return the disjunction when the known values settle it.""" 

190 unknown = False 

191 for child in self.children: 

192 value = child.evaluate_partial(known) 

193 if value is True: 

194 return True 

195 if value is None: 

196 unknown = True 

197 return None if unknown else False 

198 

199 def __repr__(self) -> str: 

200 return "(" + " | ".join(repr(child) for child in self.children) + ")" 

201 

202 

203ExprLike = Expr | str 

204 

205 

206def _coerce(value: ExprLike) -> Expr: 

207 """Coerce a bare fact name into an Atom, passing an existing Expr through. 

208 

209 Args: 

210 value (ExprLike): Either an already-built Expr, or a fact atom name. 

211 

212 Returns: 

213 Expr: ``value`` itself, or ``Atom(value)`` if it was a string. 

214 """ 

215 return Atom(value) if isinstance(value, str) else value 

216 

217 

218def all_of(*operands: ExprLike) -> Expr: 

219 """Build a conjunction from a mix of Expr nodes and bare fact atom names. 

220 

221 Args: 

222 *operands (ExprLike): Expr nodes and/or fact atom names. 

223 

224 Returns: 

225 Expr: An And of the coerced operands. 

226 """ 

227 return And(*(_coerce(operand) for operand in operands)) 

228 

229 

230def any_of(*operands: ExprLike) -> Expr: 

231 """Build a disjunction from a mix of Expr nodes and bare fact atom names. 

232 

233 Args: 

234 *operands (ExprLike): Expr nodes and/or fact atom names. 

235 

236 Returns: 

237 Expr: An Or of the coerced operands. 

238 """ 

239 return Or(*(_coerce(operand) for operand in operands)) 

240 

241 

242def no(operand: ExprLike) -> Expr: 

243 """Negate a single Expr node or bare fact atom name. 

244 

245 Args: 

246 operand (ExprLike): An Expr node, or a fact atom name. 

247 

248 Returns: 

249 Expr: A Not wrapping the coerced operand. 

250 """ 

251 return Not(_coerce(operand)) 

252 

253 

254def expr_from_json(payload: object) -> Expr: 

255 """Compile a JSON boolean expression payload (as used in the consequence catalogue) into an Expr. 

256 

257 The payload grammar is: 

258 

259 * a bare string -> Atom 

260 * ``{"not": <payload>}`` -> Not 

261 * ``{"all": [<payload>, ...]}`` -> And 

262 * ``{"any": [<payload>, ...]}`` -> Or 

263 

264 Args: 

265 payload (object): A JSON-decoded boolean expression, in the grammar above. 

266 

267 Returns: 

268 Expr: The compiled expression tree. 

269 

270 Raises: 

271 ValueError: If ``payload`` does not match the grammar above. 

272 """ 

273 if isinstance(payload, str): 

274 return Atom(payload) 

275 if isinstance(payload, dict): 

276 if "not" in payload and len(payload) == 1: 

277 return no(expr_from_json(payload["not"])) 

278 if "all" in payload and len(payload) == 1: 

279 return all_of(*(expr_from_json(item) for item in payload["all"])) 

280 if "any" in payload and len(payload) == 1: 

281 return any_of(*(expr_from_json(item) for item in payload["any"])) 

282 raise ValueError(f"Cannot compile boolean expression from payload: {payload!r}")