Skip to content

Capacities API

This page documents the concrete finite-capacity objects and validation utilities.

BaseCapacity

BaseCapacity defines the representation-independent interface used by integrals, interpretation functions and the risk package. The key semantic method is event_value(event).

BaseCapacity

Bases: ABC

Abstract interface for immutable finite capacities.

A capacity assigns a normalized, monotone value to every event in a finite universe. Concrete implementations may store a full table, sparse Möbius coefficients, or compute event values dynamically. Algorithms consume this interface through :meth:event_value and never require materialization.

Attributes

n_elements : int Number of elements in the event universe.

Notes

Capacity instances become immutable after successful validation. Subclasses should call self._freeze() at the end of construction.

n_elements abstractmethod property

n_elements: int

Number of elements in the finite capacity universe.

event_value abstractmethod

event_value(event: ArrayLike) -> float

Return the capacity value of a boolean event mask.

Source code in src/capacities_ml_fin/base/capacities/base.py
@abstractmethod
def event_value(self, event: ArrayLike) -> float:
    """Return the capacity value of a boolean event mask."""

nested_event_values

nested_event_values(order: ArrayLike) -> ndarray

Evaluate the nested upper sets induced by an element ordering.

Source code in src/capacities_ml_fin/base/capacities/base.py
def nested_event_values(self, order: ArrayLike) -> np.ndarray:
    """Evaluate the nested upper sets induced by an element ordering."""
    permutation = _order_permutation(order, self.n_elements)
    values = np.empty(self.n_elements, dtype=float)
    event = np.zeros(self.n_elements, dtype=bool)

    for position in range(self.n_elements - 1, -1, -1):
        event[permutation[position]] = True
        values[position] = self.event_value(event)

    return values

VariableUniverse

A VariableUniverse attaches stable names and indices to a finite capacity domain. Estimators create one automatically from DataFrame column names or from the fitted feature count.

VariableUniverse dataclass

VariableUniverse(var_names: Iterable[str])

Immutable names and index mapping for a finite universe.

Parameters

var_names : iterable of str Unique, non-empty variable names in their canonical order.

Attributes

var_names : tuple of str Canonical ordered variable names. n_elements : int Size of the universe. name_to_index : mapping of str to int Read-only lookup from each name to its zero-based index.

from_size classmethod

from_size(n_elements: int) -> VariableUniverse

Create a universe with generated names x0, x1, ... .

Source code in src/capacities_ml_fin/base/capacities/capacities.py
@classmethod
def from_size(cls, n_elements: int) -> "VariableUniverse":
    """Create a universe with generated names ``x0``, ``x1``, ... ."""
    if isinstance(n_elements, bool) or not isinstance(n_elements, Integral):
        raise TypeError("n_elements must be an integer.")
    if int(n_elements) < 1:
        raise ValueError("n_elements must be positive.")
    return cls(tuple(f"x{index}" for index in range(int(n_elements))))

from_coalitions classmethod

from_coalitions(
    coalitions: Iterable[CoalitionInput],
) -> VariableUniverse

Infer the smallest universe containing all observed members.

Source code in src/capacities_ml_fin/base/capacities/capacities.py
@classmethod
def from_coalitions(
    cls,
    coalitions: Iterable[CoalitionInput],
) -> "VariableUniverse":
    """Infer the smallest universe containing all observed members."""
    observed: list[int | str] = []
    seen: set[int | str] = set()
    for coalition in coalitions:
        members = (
            (coalition,)
            if isinstance(coalition, (str, Integral))
            else tuple(coalition)
        )
        for member in members:
            if (
                isinstance(member, bool)
                or not isinstance(member, (str, Integral))
            ):
                raise TypeError(
                    "Coalitions must contain only variable names or "
                    "integer indices."
                )
            normalized_member = (
                int(member) if isinstance(member, Integral) else member
            )
            if normalized_member not in seen:
                seen.add(normalized_member)
                observed.append(normalized_member)

    if not observed:
        raise ValueError(
            "The universe cannot be inferred from empty coalitions. "
            "Provide n_elements or var_names."
        )
    if all(isinstance(member, str) for member in observed):
        return cls(tuple(observed))
    if all(isinstance(member, int) for member in observed):
        if any(member < 0 for member in observed):
            raise ValueError("Variable indices must be non-negative.")
        return cls.from_size(max(observed) + 1)
    raise ValueError(
        "A universe cannot be inferred from mixed names and indices. "
        "Provide universe or var_names explicitly."
    )

ExplicitCapacity

Stores a complete table of capacity values \(\mu(A)\). Construction validates monotonicity and normalization. Use this class when the full table is known or when an explicit representation is desirable for inspection.

capacity = ExplicitCapacity(
    {
        "a": 0.3,
        "b": 0.4,
        ("a", "b"): 1.0,
    }
)

ExplicitCapacity

ExplicitCapacity(
    values: Mapping[CoalitionInput, float],
    *,
    universe: VariableUniverse | None = None,
    n_elements: int | None = None,
    var_names: Iterable[str] | None = None
)

Bases: BaseCapacity

Explicit normalized monotone capacity over a finite universe.

Parameters

values : mapping Capacity values keyed by coalitions expressed as names, indices, or iterables thereof. Every non-empty coalition must be present; the empty coalition is implicit and has value zero. universe : VariableUniverse, optional Existing universe. Mutually exclusive with n_elements and var_names. n_elements : int, optional Universe size used to generate names x0, x1, and so on. var_names : iterable of str, optional Ordered variable names. If no universe argument is supplied, the smallest universe is inferred from values.

Attributes

universe : VariableUniverse Resolved event universe. values : CapacityMap Immutable table of coalition values.

Raises

ValueError If the table is incomplete, non-normalized, or non-monotone.

Source code in src/capacities_ml_fin/base/capacities/capacities.py
def __init__(
    self,
    values: Mapping[CoalitionInput, float],
    *,
    universe: VariableUniverse | None = None,
    n_elements: int | None = None,
    var_names: Iterable[str] | None = None,
) -> None:
    self.universe = resolve_universe(
        values,
        universe=universe,
        n_elements=n_elements,
        var_names=var_names,
    )
    self.values = CapacityMap(
        capacities=[
            CoalitionValue(normalize_coalition(self.universe, coalition), value)
            for coalition, value in values.items()
        ]
    )
    self.validate()
    self._freeze()

value

value(coalition: CoalitionInput) -> float

Return the value of a coalition expressed by names or indices.

Source code in src/capacities_ml_fin/base/capacities/capacities.py
def value(self, coalition: CoalitionInput) -> float:
    """Return the value of a coalition expressed by names or indices."""
    normalized_coalition = normalize_coalition(self.universe, coalition)
    value = self.values.get_value(normalized_coalition)
    if value is None:
        raise KeyError(f"Unknown coalition: {coalition}.")
    return value

event_value

event_value(event: ArrayLike) -> float

Return the stored value of a boolean event mask.

Source code in src/capacities_ml_fin/base/capacities/capacities.py
def event_value(self, event: ArrayLike) -> float:
    """Return the stored value of a boolean event mask."""
    mask = _event_mask(event, self.n_elements)
    coalition = frozenset(int(index) for index in np.flatnonzero(mask))
    return self.value(coalition)

to_named_dict

to_named_dict() -> dict[tuple[str, ...], float]

Return the tabular capacity values keyed by variable names.

Source code in src/capacities_ml_fin/base/capacities/capacities.py
def to_named_dict(self) -> dict[tuple[str, ...], float]:
    """Return the tabular capacity values keyed by variable names."""
    return {
        named_coalition(self.universe, coalition): value
        for coalition, value in self.values.lookup_dict.items()
    }

validate

validate() -> None

Check the mathematical invariants of the capacity.

Source code in src/capacities_ml_fin/base/capacities/capacities.py
def validate(self) -> None:
    """Check the mathematical invariants of the capacity."""
    check_monotonicity(
        self.values,
        frozenset(range(self.n_elements)),
    )

KAdditiveCapacity

A concrete explicit capacity constructed from capacity values supplied for all coalitions up to order k. Higher-order values are completed from the implied low-order Möbius representation, and exact \(k\)-additivity is validated.

This object is different from ml.optimization.KAdditivity, which is a learning parameterization rather than a stored capacity.

KAdditiveCapacity

KAdditiveCapacity(
    values: Mapping[CoalitionInput, float],
    k: int,
    *,
    universe: VariableUniverse | None = None,
    n_elements: int | None = None,
    var_names: Iterable[str] | None = None
)

Bases: ExplicitCapacity

Explicit capacity reconstructed from values up to order k.

Parameters

values : mapping Capacity values for every coalition whose cardinality is at most k. Values for larger coalitions are completed from the implied low-order Möbius coefficients. k : int Exact maximum order of non-zero Möbius coefficients. Must satisfy 1 <= k <= n_elements. universe : VariableUniverse, optional Existing universe. Mutually exclusive with n_elements and var_names. n_elements : int, optional Number of elements when names are not supplied. var_names : iterable of str, optional Ordered variable names.

Attributes

k : int Validated additivity order. values : CapacityMap Completed explicit capacity table.

Raises

ValueError If required low-order coalitions are missing or the completed capacity is not normalized, monotone, and exactly k-additive.

Source code in src/capacities_ml_fin/base/capacities/k_additive.py
def __init__(
    self,
    values: Mapping[CoalitionInput, float],
    k: int,
    *,
    universe: VariableUniverse | None = None,
    n_elements: int | None = None,
    var_names: Iterable[str] | None = None,
) -> None:
    self.universe = resolve_universe(
        values,
        universe=universe,
        n_elements=n_elements,
        var_names=var_names,
    )
    self.k = k
    if not isinstance(self.k, int):
        raise TypeError("k must be an integer.")
    if not 1 <= self.k <= self.universe.n_elements:
        raise ValueError(
            f"k must satisfy 1 <= k <= n_elements, received k={self.k} "
            f"and n_elements={self.universe.n_elements}."
        )

    normalized_values: dict[frozenset[int], float] = {}
    for coalition, value in values.items():
        normalized = normalize_coalition(self.universe, coalition)
        if normalized in normalized_values:
            raise ValueError(f"Duplicate coalition found: {set(normalized)}.")
        normalized_values[normalized] = float(value)

    completed_values = self._complete_k_additive_values(normalized_values)
    super().__init__(completed_values, universe=self.universe)

MobiusCapacity

Stores a sparse map of Möbius coefficients. value(A) returns the coefficient \(m(A)\), while event_value(event) returns the capacity \(\mu(A)\) reconstructed from all stored subset coefficients.

MobiusCapacity

MobiusCapacity(
    coefficients: Mapping[CoalitionInput, float],
    *,
    universe: VariableUniverse | None = None,
    n_elements: int | None = None,
    var_names: Iterable[str] | None = None,
    validation_tolerance: float = 1e-09
)

Bases: BaseCapacity

Sparse Möbius representation of an evaluable finite capacity.

Parameters

coefficients : mapping Möbius coefficients keyed by coalitions. Unspecified coefficients are interpreted as zero; the empty coalition must not be supplied. universe : VariableUniverse, optional Existing universe. Mutually exclusive with n_elements and var_names. n_elements : int, optional Universe size when names are not supplied. var_names : iterable of str, optional Ordered variable names. validation_tolerance : float, default=1e-9 Numerical tolerance for normalization and monotonicity checks.

Attributes

universe : VariableUniverse Resolved event universe. validation_tolerance : float Tolerance used during validation.

Notes

:meth:value returns a Möbius coefficient m(A) whereas :meth:event_value reconstructs mu(A) = sum_{B subseteq A} m(B). The full capacity table is not stored.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def __init__(
    self,
    coefficients: Mapping[CoalitionInput, float],
    *,
    universe: VariableUniverse | None = None,
    n_elements: int | None = None,
    var_names: Iterable[str] | None = None,
    validation_tolerance: float = 1e-9,
) -> None:
    self.universe = resolve_universe(
        coefficients,
        universe=universe,
        n_elements=n_elements,
        var_names=var_names,
    )
    self.validation_tolerance = validation_tolerance
    self._coefficient_map = MobiusMap(
        mobius_coefficients=[
            CoalitionValue(
                normalize_coalition(self.universe, coalition),
                value,
            )
            for coalition, value in coefficients.items()
        ]
    )
    self.validate()
    self._freeze()

value

value(coalition: CoalitionInput) -> float

Return a Mobius coefficient, or zero when it is not specified.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def value(self, coalition: CoalitionInput) -> float:
    """Return a Mobius coefficient, or zero when it is not specified."""
    normalized_coalition = normalize_coalition(self.universe, coalition)
    value = self._coefficient_map.get_value(normalized_coalition)
    return 0.0 if value is None else value

event_value

event_value(event: ArrayLike) -> float

Evaluate the capacity of an event from its Mobius coefficients.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def event_value(self, event: ArrayLike) -> float:
    """Evaluate the capacity of an event from its Mobius coefficients."""
    mask = _event_mask(event, self.n_elements)
    coalition = frozenset(int(index) for index in np.flatnonzero(mask))
    return float(
        sum(
            coefficient.value
            for coefficient in self._coefficient_map
            if coefficient.coalition <= coalition
        )
    )

nested_event_values

nested_event_values(order: ArrayLike) -> ndarray

Evaluate nested events without expanding the capacity table.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def nested_event_values(self, order: ArrayLike) -> np.ndarray:
    """Evaluate nested events without expanding the capacity table."""
    permutation = _order_permutation(order, self.n_elements)
    ranks = np.empty(self.n_elements, dtype=int)
    ranks[permutation] = np.arange(self.n_elements)
    changes = np.zeros(self.n_elements + 1, dtype=float)

    for coefficient in self._coefficient_map:
        coalition = coefficient.coalition
        boundary = (
            self.n_elements - 1
            if not coalition
            else min(ranks[index] for index in coalition)
        )
        changes[0] += coefficient.value
        changes[boundary + 1] -= coefficient.value

    return np.cumsum(changes[:-1])

validate

validate() -> None

Check normalization and monotonicity of the Mobius capacity.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def validate(self) -> None:
    """Check normalization and monotonicity of the Mobius capacity."""
    check_mobius_capacity(
        self._coefficient_map,
        self.n_elements,
        tolerance=self.validation_tolerance,
    )

to_named_dict

to_named_dict() -> dict[tuple[str, ...], float]

Return the specified coefficients keyed by variable names.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def to_named_dict(self) -> dict[tuple[str, ...], float]:
    """Return the specified coefficients keyed by variable names."""
    return {
        named_coalition(self.universe, coalition): value
        for coalition, value in self._coefficient_map.lookup_dict.items()
    }

Möbius transforms

mobius_transform

Converts a complete ExplicitCapacity into an equivalent MobiusCapacity.

mobius_transform

mobius_transform(
    capacity: ExplicitCapacity,
) -> MobiusCapacity

Compute the Mobius representation of an explicit capacity.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def mobius_transform(capacity: ExplicitCapacity) -> MobiusCapacity:
    """Compute the Mobius representation of an explicit capacity."""
    if not isinstance(capacity, ExplicitCapacity):
        raise TypeError("capacity must be an ExplicitCapacity instance.")

    coefficient_map = _mobius_transform_map(capacity.values)
    return MobiusCapacity(
        coefficients=coefficient_map.to_lookup(),
        universe=capacity.universe,
    )

inverse_mobius_transform

Expands a MobiusCapacity into a complete ExplicitCapacity.

inverse_mobius_transform

inverse_mobius_transform(
    mobius_capacity: MobiusCapacity,
) -> ExplicitCapacity

Compute an explicit capacity from its Mobius representation.

Source code in src/capacities_ml_fin/base/capacities/mobius.py
def inverse_mobius_transform(
    mobius_capacity: MobiusCapacity,
) -> ExplicitCapacity:
    """Compute an explicit capacity from its Mobius representation."""
    if not isinstance(mobius_capacity, MobiusCapacity):
        raise TypeError("mobius_capacity must be a MobiusCapacity instance.")

    features = frozenset(range(mobius_capacity.n_elements))
    values: dict[frozenset[int], float] = {}
    for coalition in powerset(features):
        if coalition:
            values[coalition] = sum(
                mobius_capacity.value(subset)
                for subset in powerset(coalition)
            )

    return ExplicitCapacity(values=values, universe=mobius_capacity.universe)

Validation

validate_capacity

Exhaustively checks normalization and monotonicity on a finite event domain, subject to a configurable maximum number of elements.

validate_capacity

validate_capacity(
    capacity: BaseCapacity,
    *,
    max_elements: int = 16,
    tolerance: float = 1e-10
) -> None

Check normalization and monotonicity on a finite capacity domain.

Source code in src/capacities_ml_fin/base/capacities/validation.py
def validate_capacity(
    capacity: BaseCapacity,
    *,
    max_elements: int = 16,
    tolerance: float = 1e-10,
) -> None:
    """Check normalization and monotonicity on a finite capacity domain."""
    values = _all_event_values(capacity, max_elements)
    if not np.isclose(values[0], 0.0, atol=tolerance):
        raise ValueError("A capacity must assign zero to the empty event.")
    if not np.isclose(values[-1], 1.0, atol=tolerance):
        raise ValueError("A capacity must assign one to the full event.")

    for event in range(values.size):
        for element in range(capacity.n_elements):
            if event & (1 << element):
                continue
            superset = event | (1 << element)
            if values[event] > values[superset] + tolerance:
                raise ValueError("The capacity is not monotone.")

is_concave_capacity

Checks submodularity/concavity by exhaustive enumeration.

is_concave_capacity

is_concave_capacity(
    capacity: BaseCapacity,
    *,
    max_elements: int = 8,
    tolerance: float = 1e-10
) -> bool

Check submodularity of a capacity by exhaustive enumeration.

Source code in src/capacities_ml_fin/base/capacities/validation.py
def is_concave_capacity(
    capacity: BaseCapacity,
    *,
    max_elements: int = 8,
    tolerance: float = 1e-10,
) -> bool:
    """Check submodularity of a capacity by exhaustive enumeration."""
    values = _all_event_values(capacity, max_elements)
    for first in range(values.size):
        for second in range(values.size):
            if values[first | second] + values[first & second] > (
                values[first] + values[second] + tolerance
            ):
                return False
    return True

is_convex_capacity

Checks supermodularity/convexity by exhaustive enumeration.

is_convex_capacity

is_convex_capacity(
    capacity: BaseCapacity,
    *,
    max_elements: int = 8,
    tolerance: float = 1e-10
) -> bool

Check supermodularity of a capacity by exhaustive enumeration.

Source code in src/capacities_ml_fin/base/capacities/validation.py
def is_convex_capacity(
    capacity: BaseCapacity,
    *,
    max_elements: int = 8,
    tolerance: float = 1e-10,
) -> bool:
    """Check supermodularity of a capacity by exhaustive enumeration."""
    values = _all_event_values(capacity, max_elements)
    for first in range(values.size):
        for second in range(values.size):
            if values[first | second] + values[first & second] < (
                values[first] + values[second] - tolerance
            ):
                return False
    return True

Lower-level container types

The following immutable containers support capacity implementations. Most end users will not need to construct them directly, but they are useful when extending the package.

CoalitionValue

CoalitionValue dataclass

CoalitionValue(coalition: frozenset[int], value: float)

Immutable numeric value associated with one coalition.

CapacityMap

CapacityMap dataclass

CapacityMap(capacities: InitVar[Iterable[CoalitionValue]])

Bases: CoalitionMap

Immutable, unvalidated tabular values of a set function.

MobiusMap

MobiusMap dataclass

MobiusMap(
    mobius_coefficients: InitVar[Iterable[CoalitionValue]],
)

Bases: CoalitionMap

Immutable, potentially sparse Mobius coefficients.

Utility functions

powerset

powerset

powerset(elements: Set[int]) -> list[frozenset[int]]

Compute the power set of a coalition.

Source code in src/capacities_ml_fin/base/capacities/utils.py
def powerset(elements: Set[int]) -> list[frozenset[int]]:
    """Compute the power set of a coalition."""
    items = tuple(elements)
    return [
        frozenset(subset)
        for size in range(len(items) + 1)
        for subset in combinations(items, size)
    ]

subset_encoding

subset_encoding

subset_encoding(elements: Set[int], n_elements: int) -> int

Encode a coalition using an integer bitmask.

Source code in src/capacities_ml_fin/base/capacities/utils.py
def subset_encoding(elements: Set[int], n_elements: int) -> int:
    """Encode a coalition using an integer bitmask."""
    if n_elements < 1:
        raise ValueError("n_elements must be positive.")

    mask = 0
    for index in elements:
        if not isinstance(index, int):
            raise TypeError("Variable indices must be integers.")
        if not 0 <= index < n_elements:
            raise ValueError(
                f"Variable index {index} is invalid for n_elements={n_elements}."
            )
        mask |= 1 << index

    return mask

subset_decoding

subset_decoding

subset_decoding(
    index: int, n_elements: int
) -> frozenset[int]

Decode an integer bitmask into a coalition.

Source code in src/capacities_ml_fin/base/capacities/utils.py
def subset_decoding(index: int, n_elements: int) -> frozenset[int]:
    """Decode an integer bitmask into a coalition."""
    if not isinstance(index, int):
        raise TypeError("index must be an integer.")

    maximum_index = (1 << n_elements) - 1
    if not 0 <= index <= maximum_index:
        raise ValueError(f"index must be between 0 and {maximum_index}.")

    return frozenset(
        variable
        for variable in range(n_elements)
        if index & (1 << variable)
    )