Source code for spflow.zoo.mc.config

"""Configuration of the membership test of a Membership Circuit."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Literal, get_args

from spflow.exceptions import InvalidParameterError, InvalidTypeError
from spflow.zoo.mc.combination import ProductCombination, SumCombination

Side = Literal["both", "left", "right"]
DiscreteMode = Literal["exact", "midp", "randomized"]


[docs] @dataclass(frozen=True) class MembershipTestConfig: """Configuration of a membership test. Attributes: sum_rule: Combination rule used at every sum node. product_rule: Combination rule used at every product node. side: Test side of every leaf. ``"left"`` rejects small values, ``"right"`` rejects large values and ``"both"`` rejects values in either tail. discrete_mode: P-value definition at discrete leaves. ``"exact"`` is valid and conservative. ``"midp"`` counts half of the observed atom and is not a valid p-value in general. ``"randomized"`` is exactly uniform under the leaf distribution, at the price of a random decision. Raises: InvalidTypeError: If ``sum_rule`` is not a :class:`SumCombination` or ``product_rule`` is not a :class:`ProductCombination`, or if the ``name`` of a rule is not a non-empty string. InvalidParameterError: If ``side`` or ``discrete_mode`` has an unknown value. """ sum_rule: SumCombination product_rule: ProductCombination side: Side = "both" discrete_mode: DiscreteMode = "exact" def __post_init__(self) -> None: if not isinstance(self.sum_rule, SumCombination): raise InvalidTypeError( f"sum_rule must be a SumCombination, got {type(self.sum_rule).__name__}. " "A rule that is not a SumCombination is not a valid test at sum nodes." ) if not isinstance(self.product_rule, ProductCombination): raise InvalidTypeError( f"product_rule must be a ProductCombination, got {type(self.product_rule).__name__}. " "A rule that is not a ProductCombination is not a valid test at product nodes." ) for role, rule in (("sum_rule", self.sum_rule), ("product_rule", self.product_rule)): name = getattr(rule, "name", None) if not isinstance(name, str) or not name: raise InvalidTypeError( f"{role} of type {type(rule).__name__} needs a non-empty string as its attribute " f"'name', got {name!r}." ) if self.side not in get_args(Side): raise InvalidParameterError(f"Unknown side '{self.side}'. Use one of {get_args(Side)}.") if self.discrete_mode not in get_args(DiscreteMode): raise InvalidParameterError( f"Unknown discrete_mode '{self.discrete_mode}'. Use one of {get_args(DiscreteMode)}." )
[docs] def name(self) -> str: """Return a stable identifier of the configuration. Returns: ``"{side}_S_{sum rule}_P_{product rule}"``, followed by ``"_D_{discrete_mode}"`` if the discrete mode is not ``"exact"``. """ name = f"{self.side}_S_{self.sum_rule.name}_P_{self.product_rule.name}" if self.discrete_mode != "exact": name += f"_D_{self.discrete_mode}" return name