Coverage for src/python/ensembl/vep/annotators/consequence/rules/rulesets.py: 99%
80 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"""Compile and evaluate rank-ordered consequence rules.
16Rules do not reference other rules. Subsumption expresses suppression between firing terms, while
17``FactRule.cheap_guard`` derives inexpensive preconditions directly from each formula. Keeping both
18relationships declarative prevents hand-maintained predicates or guard tables from drifting.
19"""
21from __future__ import annotations
23from collections.abc import Iterable
24from functools import cache
26from attrs import field, frozen
28from ensembl.vep.annotators.consequence.rules.catalogue import (
29 DEFAULT_TERM,
30 ConsequenceDefinition,
31 load_consequence_definitions,
32)
33from ensembl.vep.annotators.consequence.rules.expressions import And, Atom, Expr, expr_from_json
34from ensembl.vep.annotators.consequence.facts.base import closure_cost
35from ensembl.vep.common import ConsequenceImpact, CostTier
36from ensembl.vep.models import Feature
37from ensembl.vep.models.overlap import OverlapConsequence
38from ensembl.vep.models.variation import VariationAllele
40_CODING_ATOM = "overlap_cds"
41"""The fact a rule must read to count as coding."""
43__all__ = [
44 "DEFAULT_TERM",
45 "FactRule",
46 "FactRuleSet",
47 "build_fact_ruleset",
48 "build_fact_ruleset_from_definitions",
49 "coding_terms",
50 "prune",
51 "subsumes_topological_order",
52]
55@frozen(kw_only=True, auto_attribs=True)
56class FactRule:
57 """Represent one SO term as a Boolean formula and catalogue metadata.
59 Attributes:
60 term (str): The SO term, e.g. "missense_variant".
61 accession (str): The SO accession, e.g. "SO:0001583".
62 rank (int): Severity rank; 1 is most severe.
63 tier (int): Tier grouping, carried through from the catalogue.
64 impact (ConsequenceImpact | None): The IMPACT rating.
65 when (Expr): The boolean formula over fact atoms that must hold for this term to apply.
66 subsumes (tuple[str, ...]): Term names this rule suppresses when evaluated as true.
67 feature_type (type[Feature]): The overlapped feature type this rule applies to.
68 overlapping_feature_type (type[Feature]): The overlapping feature type (variant allele).
69 notes (str | None): Free-text notes, if any.
70 """
72 term: str
73 accession: str
74 rank: int
75 tier: int = field(default=3)
76 impact: ConsequenceImpact | None
77 when: Expr
78 subsumes: tuple[str, ...] = field(default=())
79 feature_type: type[Feature] = field(default=Feature)
80 overlapping_feature_type: type[Feature] = field(default=VariationAllele)
81 notes: str | None = field(default=None)
83 def atoms(self) -> set[str]:
84 """Return every fact atom referenced by this rule.
86 Returns:
87 set[str]: The referenced fact atom names.
88 """
89 return self.when.atoms()
91 def cheap_guard(self) -> frozenset[str]:
92 """Return inexpensive top-level positive conjuncts.
94 This is the automatically-derived equivalent of VEP's hand-maintained ``include`` hash.
96 Returns:
97 frozenset[str]: Names of top-level atoms in a top-level conjunction whose
98 closure cost is at most BOUNDS.
99 """
100 conjuncts: tuple[Expr, ...] = self.when.children if isinstance(self.when, And) else (self.when,)
101 cheap_atoms = set()
102 for conjunct in conjuncts:
103 if isinstance(conjunct, Atom) and closure_cost(conjunct.name) <= CostTier.BOUNDS:
104 cheap_atoms.add(conjunct.name)
105 return frozenset(cheap_atoms)
107 def to_overlap_consequence(self) -> OverlapConsequence:
108 """Convert this rule into an OverlapConsequence output object.
110 Returns:
111 OverlapConsequence: The corresponding output consequence, with ``is_default=False``.
112 """
113 return OverlapConsequence(
114 term=self.term,
115 accession=self.accession,
116 is_default=False,
117 rank=self.rank,
118 tier=self.tier,
119 impact=self.impact,
120 feature_type=self.feature_type,
121 overlapping_feature_type=self.overlapping_feature_type,
122 )
125@frozen(kw_only=True, auto_attribs=True)
126class FactRuleSet:
127 """Store rank-ordered fact rules and term lookup.
129 Covers **every** overlapped-feature class, and there is no per-class subset to select: a
130 rule restricted to one class says so in its own formula, via the FREE class facts in
131 consequence/facts/kind.py. See build_fact_ruleset.
133 Attributes:
134 rules (tuple[FactRule, ...]): Every rule, sorted by ascending rank.
135 by_term (dict[str, FactRule]): Rules keyed by term name.
136 """
138 rules: tuple[FactRule, ...]
139 by_term: dict[str, FactRule] = field(init=False)
141 def __attrs_post_init__(self) -> None:
142 object.__setattr__(self, "by_term", {rule.term: rule for rule in self.rules})
145def build_fact_ruleset_from_definitions(
146 definitions: Iterable[ConsequenceDefinition],
147) -> FactRuleSet:
148 """Compile a rule set from catalogue definitions.
150 The single compilation path: ``build_fact_ruleset`` reads the packaged catalogue and delegates
151 here, and the catalogue editor compiles its candidate entries the same way, so a change cannot
152 validate against a rule set built differently from the one the annotators will use.
154 Entries with no ``when`` (see EXCLUDED_TERMS in consequence/rules/catalogue.py) are skipped,
155 since there is no fact-atom formula to compile for them.
157 Args:
158 definitions (Iterable[ConsequenceDefinition]): The entries to compile.
160 Returns:
161 FactRuleSet: The compiled, rank-ordered rule set.
162 """
163 compilable = [definition for definition in definitions if definition.when is not None]
164 rules = tuple(
165 FactRule(
166 term=definition.term,
167 accession=definition.accession,
168 rank=definition.rank,
169 impact=definition.impact,
170 when=expr_from_json(definition.when),
171 subsumes=definition.subsumes,
172 tier=definition.tier,
173 notes=definition.notes,
174 )
175 for definition in sorted(compilable, key=lambda definition: definition.rank)
176 )
177 return FactRuleSet(rules=rules)
180def build_fact_ruleset() -> FactRuleSet:
181 """Compile a FactRuleSet from the packaged consequence catalogue.
183 Returns:
184 FactRuleSet: The compiled, rank-ordered rule set, covering every feature class.
185 """
186 return build_fact_ruleset_from_definitions(load_consequence_definitions())
189@cache
190def coding_terms() -> frozenset[str]:
191 """Return the catalogue terms whose rule reads ``overlap_cds``.
193 Derived rather than tabulated: a rule that reads the CDS is a coding rule, and that is the
194 whole definition.
195 """
196 return frozenset(rule.term for rule in build_fact_ruleset().rules if _CODING_ATOM in rule.when.atoms())
199def subsumes_topological_order(ruleset: FactRuleSet) -> tuple[FactRule, ...]:
200 """Order the rules so a rule comes after a rule that can suppress it.
202 After every rule has been evaluated, the subsumed terms are dropped. A rule whose term is
203 certain to be suppressed by a higher-ranked term therefore evaluated for nothing. Evaluating
204 in this order instead lets a scan skip such a rule outright.
206 The ``subsumes`` graph is acyclic. The ``RulePairFinding.contradictory_in`` and
207 ``find_subsumption_cycles`` in rules/validation.py both reject cycles. So, a depth-first
208 post-order is a valid topological sort. A cycle, were one ever introduced, it would not
209 degrade to an infinite loop, and the conformance suite would catch the resulting output difference.
211 Args:
212 ruleset (FactRuleSet): The rule set to order.
214 Returns:
215 tuple[FactRule, ...]: Every rule in ``ruleset``, ordered so that a rule appears after
216 every rule that (transitively) subsumes it.
217 """
218 rules_by_rank = sorted(ruleset.rules, key=lambda rule: rule.rank)
219 suppressors: dict[str, list[str]] = {rule.term: [] for rule in rules_by_rank}
220 for rule in rules_by_rank:
221 for subsumed_term in rule.subsumes:
222 if subsumed_term in suppressors: 222 ↛ 221line 222 didn't jump to line 221 because the condition on line 222 was always true
223 suppressors[subsumed_term].append(rule.term)
225 ordered: list[FactRule] = []
226 visit_state: dict[str, int] = {} # 0/absent = unvisited, 1 = in progress, 2 = emitted
228 def visit(term: str) -> None:
229 if visit_state.get(term, 0) != 0:
230 return
231 visit_state[term] = 1
232 for suppressor_term in suppressors[term]:
233 visit(suppressor_term)
234 visit_state[term] = 2
235 ordered.append(ruleset.by_term[term])
237 for rule in rules_by_rank:
238 visit(rule.term)
239 return tuple(ordered)
242def prune(ruleset: FactRuleSet, hit_terms: list[str], *, apply_default: bool = True) -> list[str]:
243 """Drop terms superseded by another term that fired.
245 Args:
246 ruleset (FactRuleSet): The rule set ``hit_terms`` were matched against.
247 hit_terms (list[str]): Every term whose rule matched, in any order.
248 apply_default (bool): If True, substitute ``[DEFAULT_TERM]`` when nothing survives pruning.
249 If False, return an empty list instead and let the caller decide whether/how to apply a
250 default term.
252 Returns:
253 list[str]: ``hit_terms`` with every subsumed term removed. Empty (if ``apply_default`` is
254 False) or ``[DEFAULT_TERM]`` (otherwise) when nothing survives.
255 """
256 dropped: set[str] = set()
257 for term in hit_terms:
258 dropped.update(ruleset.by_term[term].subsumes)
259 kept = [term for term in hit_terms if term not in dropped]
260 if kept or not apply_default:
261 return kept
262 return [DEFAULT_TERM]