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
« 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."""
16from __future__ import annotations
18from typing import TYPE_CHECKING
20from attrs import field, frozen
22from ensembl.vep.annotators.consequence.facts.base import get_fact, total_cost
24if TYPE_CHECKING:
25 from ensembl.vep.annotators.consequence.context.fact import FactContext
27__all__ = ["And", "Atom", "Expr", "Not", "Or", "all_of", "any_of", "expr_from_json", "no"]
30class Expr:
31 """Represent a Boolean expression over fact atoms."""
33 def atoms(self) -> set[str]:
34 """Return every fact atom referenced by this expression.
36 Returns:
37 set[str]: The referenced fact atom names.
38 """
39 raise NotImplementedError
41 def evaluate(self, fact_context: FactContext) -> bool:
42 """Evaluate this expression against a fact context, computing facts as needed.
44 Args:
45 fact_context (FactContext): The overlap to evaluate against.
47 Returns:
48 bool: The expression's truth value.
49 """
50 raise NotImplementedError
52 def cost(self) -> int:
53 """Return the cold cost of evaluating this expression.
55 Returns:
56 int: The total cost of every atom referenced, counting each shared dependency once.
57 """
58 return total_cost(self.atoms())
60 def evaluate_partial(self, known: dict[str, bool]) -> bool | None:
61 """Evaluate this expression against a partial (Kleene) assignment.
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.
67 Args:
68 known (dict[str, bool]): A partial assignment of fact atom names to boolean values.
70 Returns:
71 bool | None: The expression's truth value if settled by ``known``, else None.
72 """
73 raise NotImplementedError
75 def __and__(self, other: Expr) -> Expr:
76 return And(self, other)
78 def __or__(self, other: Expr) -> Expr:
79 return Or(self, other)
81 def __invert__(self) -> Expr:
82 return Not(child=self)
85@frozen(kw_only=False, auto_attribs=True)
86class Atom(Expr):
87 """Represent one fact atom by name."""
89 name: str
91 def atoms(self) -> set[str]:
92 """Return this atom's name."""
93 return {self.name}
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))
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)
103 def __repr__(self) -> str:
104 return self.name
107@frozen(kw_only=False, auto_attribs=True)
108class Not(Expr):
109 """Negate one child expression."""
111 child: Expr
113 def atoms(self) -> set[str]:
114 """Return the atoms referenced by the child expression."""
115 return self.child.atoms()
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)
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
126 def __repr__(self) -> str:
127 return f"!{self.child!r}"
130@frozen(kw_only=False, auto_attribs=True, init=False)
131class And(Expr):
132 """Combine child expressions with logical conjunction."""
134 children: tuple[Expr, ...] = field()
136 def __init__(self, *children: Expr) -> None:
137 object.__setattr__(self, "children", tuple(children))
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()
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
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
164 def __repr__(self) -> str:
165 return "(" + " & ".join(repr(child) for child in self.children) + ")"
168@frozen(kw_only=False, auto_attribs=True, init=False)
169class Or(Expr):
170 """Combine child expressions with logical disjunction."""
172 children: tuple[Expr, ...] = field()
174 def __init__(self, *children: Expr) -> None:
175 object.__setattr__(self, "children", tuple(children))
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()
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
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
199 def __repr__(self) -> str:
200 return "(" + " | ".join(repr(child) for child in self.children) + ")"
203ExprLike = Expr | str
206def _coerce(value: ExprLike) -> Expr:
207 """Coerce a bare fact name into an Atom, passing an existing Expr through.
209 Args:
210 value (ExprLike): Either an already-built Expr, or a fact atom name.
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
218def all_of(*operands: ExprLike) -> Expr:
219 """Build a conjunction from a mix of Expr nodes and bare fact atom names.
221 Args:
222 *operands (ExprLike): Expr nodes and/or fact atom names.
224 Returns:
225 Expr: An And of the coerced operands.
226 """
227 return And(*(_coerce(operand) for operand in operands))
230def any_of(*operands: ExprLike) -> Expr:
231 """Build a disjunction from a mix of Expr nodes and bare fact atom names.
233 Args:
234 *operands (ExprLike): Expr nodes and/or fact atom names.
236 Returns:
237 Expr: An Or of the coerced operands.
238 """
239 return Or(*(_coerce(operand) for operand in operands))
242def no(operand: ExprLike) -> Expr:
243 """Negate a single Expr node or bare fact atom name.
245 Args:
246 operand (ExprLike): An Expr node, or a fact atom name.
248 Returns:
249 Expr: A Not wrapping the coerced operand.
250 """
251 return Not(_coerce(operand))
254def expr_from_json(payload: object) -> Expr:
255 """Compile a JSON boolean expression payload (as used in the consequence catalogue) into an Expr.
257 The payload grammar is:
259 * a bare string -> Atom
260 * ``{"not": <payload>}`` -> Not
261 * ``{"all": [<payload>, ...]}`` -> And
262 * ``{"any": [<payload>, ...]}`` -> Or
264 Args:
265 payload (object): A JSON-decoded boolean expression, in the grammar above.
267 Returns:
268 Expr: The compiled expression tree.
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}")