Skip to content

Algebras

An Algebra fixes how composition combines weights: a product \(\otimes\) along a path and a reduction \(\oplus\) across alternative paths. Each built-in instance is a semiring (Goodman, 1999; Mohri, 2002), a t-norm with its t-conorm (Klement et al., 2000), or a product with capped sum. Multiplication with summation gives the ordinary matrix product, and addition with minimum gives shortest path costs. Composition is associative only when \(\otimes\) is associative and distributes over \(\oplus\) (Kelly, 1982). The instances whose operations satisfy the semiring laws are of class Semiring, and those whose \(\oplus\) is also idempotent of class IdempotentSemiring. The default product t-norm with noisy-OR reduction does not distribute, so it is an Algebra only, and with it a change of grouping can change the result.

algebras

Algebras: the operations that parameterize tensor composition.

A commutative algebra Q = (L, ⊗, ⋁, ⋀, ¬, I, ⊥) defines the composition of L-valued matrices

(g ∘ f)(a, c) = ⋁_b f(a, b) ⊗ g(b, c)

and the identity matrix (I on the diagonal, ⊥ elsewhere). Composition is associative exactly when the operations satisfy the semiring laws; those algebras are instances of Semiring, and for them finite sets and L-valued matrices form a category (for instance Rel under BooleanAlgebra, or finite stochastic matrices under MarkovAlgebra). The remaining algebras, such as the default ProductFuzzyAlgebra (product with noisy-OR), fail distributivity, so their composition is unital but depends on bracketing. join names the implemented reduction and is a lattice supremum only for an IdempotentSemiring.

The classes form one hierarchy. Each class states the laws its members satisfy as quivers.core.laws.Law records, and every member reports, for each law it claims, a quivers.core.laws.LawClaim whose evidence is a written argument, a decision procedure, a test on finite data, or a declaration. Executors ask for a capability by type: Selective sums return one of their operands, ZeroSumFree and NoZeroDivisors make support a homomorphism, a Semifield divides, a Ring subtracts, and a Semimodule is acted on by a semiring. A Carrier gives the zero (and a UnitalCarrier the unit) in the shape, dtype and device a computation needs, decides membership, and returns the zero for a reduction over no terms.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

Carrier

Bases: Lawful

A set of values held in tensors, with a zero and a sum.

One element of the carrier occupies the trailing element_shape axes of a tensor; the leading axes index elements. A scalar carrier has element_shape == (). The zero is given in the shape, dtype and device a computation needs, so no computation makes it in the default dtype. join reduces index axes by the sum, and a reduction over no terms is the zero, with a derivative that is a number.

element_shape abstractmethod property

element_shape: tuple[int, ...]

The trailing axes of one element.

RETURNS DESCRIPTION
tuple of int

() for a scalar carrier.

zero_like abstractmethod

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The zero at every index of shape.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device the zero takes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The zero with shape (*shape, *element_shape), which does not require a gradient.

RAISES DESCRIPTION
TypeError

If the dtype of like cannot hold the zero.

Source code in src/quivers/core/algebras.py
@abstractmethod
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The zero at every index of ``shape``.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device the zero takes.

    Returns
    -------
    torch.Tensor
        The zero with shape ``(*shape, *element_shape)``, which does
        not require a gradient.

    Raises
    ------
    TypeError
        If the dtype of ``like`` cannot hold the zero.
    """
    ...

contains abstractmethod

contains(t: Tensor) -> Tensor

Whether each element of t lies in the carrier.

PARAMETER DESCRIPTION
t

Elements with trailing element_shape axes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A Boolean tensor of the index shape of t.

RAISES DESCRIPTION
TypeError

If the entries are complex, or the carrier is not declared.

Source code in src/quivers/core/algebras.py
@abstractmethod
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Whether each element of ``t`` lies in the carrier.

    Parameters
    ----------
    t : torch.Tensor
        Elements with trailing ``element_shape`` axes.

    Returns
    -------
    torch.Tensor
        A Boolean tensor of the index shape of ``t``.

    Raises
    ------
    TypeError
        If the entries are complex, or the carrier is not declared.
    """
    ...

join abstractmethod

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The sum ⊕ over index axes.

PARAMETER DESCRIPTION
t

Elements with trailing element_shape axes.

TYPE: Tensor

dim

Index axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The reduction with the named axes removed.

Source code in src/quivers/core/algebras.py
@abstractmethod
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The sum ⊕ over index axes.

    Parameters
    ----------
    t : torch.Tensor
        Elements with trailing ``element_shape`` axes.
    dim : int or tuple of int
        Index axes to reduce.

    Returns
    -------
    torch.Tensor
        The reduction with the named axes removed.
    """
    ...

join_pair

join_pair(a: Tensor, b: Tensor) -> Tensor

The binary sum a ⊕ b, with a first in declared order.

PARAMETER DESCRIPTION
a

The first operand.

TYPE: Tensor

b

The second operand, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The sum, computed as join over a new leading axis holding a then b.

Source code in src/quivers/core/algebras.py
def join_pair(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The binary sum ``a ⊕ b``, with ``a`` first in declared order.

    Parameters
    ----------
    a : torch.Tensor
        The first operand.
    b : torch.Tensor
        The second operand, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        The sum, computed as `join` over a new leading axis holding
        ``a`` then ``b``.
    """
    return _pair(self.join, a, b)

is_zero

is_zero(t: Tensor) -> Tensor

Whether each element of t is exactly the zero.

PARAMETER DESCRIPTION
t

Elements with trailing element_shape axes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A Boolean tensor of the index shape of t.

Source code in src/quivers/core/algebras.py
def is_zero(self, t: torch.Tensor) -> torch.Tensor:
    """Whether each element of ``t`` is exactly the zero.

    Parameters
    ----------
    t : torch.Tensor
        Elements with trailing ``element_shape`` axes.

    Returns
    -------
    torch.Tensor
        A Boolean tensor of the index shape of ``t``.
    """
    rank = len(self.element_shape)
    index = tuple(t.shape[: t.ndim - rank])
    equal = t == self.zero_like(index, t)
    for _ in range(rank):
        equal = equal.all(dim=-1)
    return equal

validate

validate(t: Tensor) -> None

Require every element of t to lie in the carrier.

PARAMETER DESCRIPTION
t

Elements with trailing element_shape axes.

TYPE: Tensor

RAISES DESCRIPTION
TypeError

If the entries are complex, or the carrier is not declared.

ValueError

If an element lies outside the carrier.

Source code in src/quivers/core/algebras.py
def validate(self, t: torch.Tensor) -> None:
    """Require every element of ``t`` to lie in the carrier.

    Parameters
    ----------
    t : torch.Tensor
        Elements with trailing ``element_shape`` axes.

    Raises
    ------
    TypeError
        If the entries are complex, or the carrier is not declared.
    ValueError
        If an element lies outside the carrier.
    """
    validate_carrier(t, self)

empty_join

empty_join(t: Tensor, axes: tuple[int, ...]) -> Tensor

The join over normalized axes one of which has size zero.

PARAMETER DESCRIPTION
t

Elements with trailing element_shape axes.

TYPE: Tensor

axes

Normalized index axes, one of size zero.

TYPE: tuple of int

RETURNS DESCRIPTION
Tensor

The zero of the remaining index shape in the dtype and device of t, on the autograd graph of t so its derivative is zero.

Source code in src/quivers/core/algebras.py
def empty_join(self, t: torch.Tensor, axes: tuple[int, ...]) -> torch.Tensor:
    """The join over normalized axes one of which has size zero.

    Parameters
    ----------
    t : torch.Tensor
        Elements with trailing ``element_shape`` axes.
    axes : tuple of int
        Normalized index axes, one of size zero.

    Returns
    -------
    torch.Tensor
        The zero of the remaining index shape in the dtype and device
        of ``t``, on the autograd graph of ``t`` so its derivative is
        zero.
    """
    rank = len(self.element_shape)
    remaining = reduced_shape(t, axes)
    index = remaining[: len(remaining) - rank]
    return empty_reduction(t, axes, self.zero_like(index, t))

UnitalCarrier

Bases: Carrier

A carrier with a product ⊗ and its unit.

The unit, like the zero, is given in the shape, dtype and device a computation needs.

tensor_op abstractmethod

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product ⊗ of elements, broadcast over index axes.

PARAMETER DESCRIPTION
a

The left factor.

TYPE: Tensor

b

The right factor.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊗ b, with a on the left.

Source code in src/quivers/core/algebras.py
@abstractmethod
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product ⊗ of elements, broadcast over index axes.

    Parameters
    ----------
    a : torch.Tensor
        The left factor.
    b : torch.Tensor
        The right factor.

    Returns
    -------
    torch.Tensor
        ``a ⊗ b``, with ``a`` on the left.
    """
    ...

unit_like abstractmethod

unit_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The unit at every index of shape.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device the unit takes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The unit with shape (*shape, *element_shape), which does not require a gradient.

RAISES DESCRIPTION
TypeError

If the dtype of like cannot hold the unit.

Source code in src/quivers/core/algebras.py
@abstractmethod
def unit_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The unit at every index of ``shape``.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device the unit takes.

    Returns
    -------
    torch.Tensor
        The unit with shape ``(*shape, *element_shape)``, which does
        not require a gradient.

    Raises
    ------
    TypeError
        If the dtype of ``like`` cannot hold the unit.
    """
    ...

identity_tensor

identity_tensor(obj_shape: tuple[int, ...], *, dtype: dtype | None = None, device: device | str | None = None) -> Tensor

The identity matrix of an object of the given shape.

PARAMETER DESCRIPTION
obj_shape

The shape of the object, for instance (n,) for a finite set of n elements.

TYPE: tuple of int

dtype

The dtype; None means torch's default dtype, as in torch.full.

TYPE: dtype or None DEFAULT: None

device

The device; None means torch's default device.

TYPE: device or str or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape (*obj_shape, *obj_shape, *element_shape), the unit on the diagonal and the zero elsewhere.

Source code in src/quivers/core/algebras.py
def identity_tensor(
    self,
    obj_shape: tuple[int, ...],
    *,
    dtype: torch.dtype | None = None,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    """The identity matrix of an object of the given shape.

    Parameters
    ----------
    obj_shape : tuple of int
        The shape of the object, for instance ``(n,)`` for a finite
        set of ``n`` elements.
    dtype : torch.dtype or None
        The dtype; ``None`` means torch's default dtype, as in
        ``torch.full``.
    device : torch.device or str or None
        The device; ``None`` means torch's default device.

    Returns
    -------
    torch.Tensor
        Shape ``(*obj_shape, *obj_shape, *element_shape)``, the unit
        on the diagonal and the zero elsewhere.
    """
    like = torch.empty(0, dtype=dtype, device=device)
    full = tuple(obj_shape) + tuple(obj_shape)
    size = math.prod(obj_shape)
    diagonal = torch.eye(size, dtype=torch.bool, device=like.device).reshape(full)
    diagonal = diagonal.reshape(*full, *([1] * len(self.element_shape)))
    return torch.where(
        diagonal, self.unit_like(full, like), self.zero_like(full, like)
    )

CompositionRule

Bases: Lawful

A binary tensor contraction that promises no algebraic law.

Defines the V-enriched composition kernel (f >> g)[i, k] = ⋁_j f[i, j] ⊗ g[j, k] from the two primitive operations tensor_op (binary ⊗) and join (reduction ⋁). No identity element is required at this level.

The hierarchy below this class records which laws composition satisfies:

  • Magmoid: composition is declared to satisfy no law, so the caller fixes every association order.
  • Semigroupoid: composition is associative.
  • OrderPreservingSemiring: a semiring whose product need not commute, so composition is associative and unital but keeps the order of its factors.
  • Algebra: a scalar carrier with unit and zero (and meet and negation), so composition has two-sided identities. Associativity is not implied.
  • Semiring: an Algebra whose operations satisfy the commutative-semiring laws, which makes composition associative and unital, so finite sets and tensors form a category.
  • IdempotentSemiring: a Semiring whose join is idempotent.

Operations that need identity check at runtime that the composition rule is at least an Algebra; a clear error is raised if a non-algebra rule is fed in.

tensor_op abstractmethod

tensor_op(a: Tensor, b: Tensor) -> Tensor

Monoidal product ⊗ (elementwise).

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊗ b.

Source code in src/quivers/core/algebras.py
@abstractmethod
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Monoidal product ⊗ (elementwise).

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        ``a ⊗ b``.
    """
    ...

join abstractmethod

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

Join ⋁, the reduction of composition.

PARAMETER DESCRIPTION
t

Input tensor.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The reduction with the named axes removed.

Source code in src/quivers/core/algebras.py
@abstractmethod
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """Join ⋁, the reduction of composition.

    Parameters
    ----------
    t : torch.Tensor
        Input tensor.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The reduction with the named axes removed.
    """
    ...

join_pair

join_pair(a: Tensor, b: Tensor) -> Tensor

The binary join a ⋁ b, with a first in declared order.

PARAMETER DESCRIPTION
a

The first operand.

TYPE: Tensor

b

The second operand, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The join over a new leading axis holding a then b.

Source code in src/quivers/core/algebras.py
def join_pair(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The binary join ``a ⋁ b``, with ``a`` first in declared order.

    Parameters
    ----------
    a : torch.Tensor
        The first operand.
    b : torch.Tensor
        The second operand, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        The join over a new leading axis holding ``a`` then ``b``.
    """
    return _pair(self.join, a, b)

compose

compose(m: Tensor, n: Tensor, n_contract: int) -> Tensor

V-enriched composition of scalar-valued tensors.

Computes result[d..., c...] = ⋁_{s...} m[d..., s...] ⊗ n[s..., c...].

PARAMETER DESCRIPTION
m

Left tensor of shape (*domain, *shared).

TYPE: Tensor

n

Right tensor of shape (*shared, *codomain).

TYPE: Tensor

n_contract

Number of shared axes to contract.

TYPE: int

RETURNS DESCRIPTION
Tensor

Composed tensor of shape (*domain, *codomain).

RAISES DESCRIPTION
ValueError

If n_contract is below one or the shared axes differ.

Source code in src/quivers/core/algebras.py
def compose(
    self,
    m: torch.Tensor,
    n: torch.Tensor,
    n_contract: int,
) -> torch.Tensor:
    """V-enriched composition of scalar-valued tensors.

    Computes ``result[d..., c...] = ⋁_{s...} m[d..., s...] ⊗ n[s..., c...]``.

    Parameters
    ----------
    m : torch.Tensor
        Left tensor of shape ``(*domain, *shared)``.
    n : torch.Tensor
        Right tensor of shape ``(*shared, *codomain)``.
    n_contract : int
        Number of shared axes to contract.

    Returns
    -------
    torch.Tensor
        Composed tensor of shape ``(*domain, *codomain)``.

    Raises
    ------
    ValueError
        If ``n_contract`` is below one or the shared axes differ.
    """
    if n_contract < 1:
        raise ValueError(f"n_contract must be >= 1, got {n_contract}")
    shared_m = m.shape[-n_contract:]
    shared_n = n.shape[:n_contract]
    if shared_m != shared_n:
        raise ValueError(
            f"shared dimensions do not match: "
            f"m trailing {shared_m} != n leading {shared_n}"
        )
    return _composite(self, m, n, n_contract, 0)

is_compatible

is_compatible(other: CompositionRule) -> bool

Whether two rules compose: the same type, or the same name.

PARAMETER DESCRIPTION
other

The other rule.

TYPE: CompositionRule

RETURNS DESCRIPTION
bool

True when morphisms over the two rules may compose; a custom instance built independently matches by name.

Source code in src/quivers/core/algebras.py
def is_compatible(self, other: CompositionRule) -> bool:
    """Whether two rules compose: the same type, or the same name.

    Parameters
    ----------
    other : CompositionRule
        The other rule.

    Returns
    -------
    bool
        True when morphisms over the two rules may compose; a
        custom instance built independently matches by name.
    """
    if type(self) is type(other):
        return True
    return self.name == other.name

Semigroupoid

Bases: CompositionRule

A composition rule whose composition is associative.

A semigroupoid is a category without the requirement of identity morphisms: composition is defined for composable pairs and is associative [Tilson (1987)]. A CompositionRule belongs here when (f >> g) >> h == f >> (g >> h) for all composable tensors. Associativity of the scalar tensor_op alone does not suffice: matrix composition also needs join to be associative and commutative and tensor_op to distribute over it.

References

Tilson, B. (1987). Categories as algebra: an essential ingredient in the theory of monoids. Journal of Pure and Applied Algebra, 48(1-2), 83-198. doi:10.1016/0022-4049(87)90108-3

Magmoid

Bases: CompositionRule

A composition rule declared to satisfy no law.

A magmoid is a quiver with a binary composition operation and no further axioms: neither associativity nor identities are required [Arnold and Dauchet (1978)]. It is to a category what a magma is to a monoid. (f >> g) >> h may differ from f >> (g >> h), so callers fix an association order explicitly, and the type records that composition chains may not be reordered.

Examples include signed-dot-product compositions, top-k truncating compositions, and the material-implication rule of material_implication. A rule that is associative should be declared as a Semigroupoid instead.

References

Arnold, A., and Dauchet, M. (1978). Théorie des magmoïdes (I). RAIRO Informatique théorique, 12(3), 235-257. doi:10.1051/ita/1978120302351

OrderPreservingSemiring

Bases: Semigroupoid, UnitalCarrier

A semiring whose product need not commute.

(L, ⊕, 0) is a commutative monoid, (L, ⊗, 1) a monoid, ⊗ distributes over ⊕ on both sides and 0 annihilates ⊗ [Golan (1999)]. Matrices over it compose associatively and unitally, but a composite keeps the order of its factors: a plan over such weights may reorder sums and may not exchange factors. Elements may have shape, as the square matrices of MatrixSemiring do; composition contracts index axes and keeps each element's trailing axes.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

compose

compose(m: Tensor, n: Tensor, n_contract: int) -> Tensor

Composition of element-valued tensors, keeping factor order.

Computes result[d..., c...] = ⊕_{s...} m[d..., s...] ⊗ n[s..., c...] with m's element on the left of every product.

PARAMETER DESCRIPTION
m

Shape (*domain, *shared, *element_shape).

TYPE: Tensor

n

Shape (*shared, *codomain, *element_shape).

TYPE: Tensor

n_contract

Number of shared index axes to contract.

TYPE: int

RETURNS DESCRIPTION
Tensor

Shape (*domain, *codomain, *element_shape).

RAISES DESCRIPTION
ValueError

If n_contract is below one, the shared axes differ, or an operand lacks the element axes.

Source code in src/quivers/core/algebras.py
def compose(
    self,
    m: torch.Tensor,
    n: torch.Tensor,
    n_contract: int,
) -> torch.Tensor:
    """Composition of element-valued tensors, keeping factor order.

    Computes ``result[d..., c...] = ⊕_{s...} m[d..., s...] ⊗ n[s..., c...]``
    with ``m``'s element on the left of every product.

    Parameters
    ----------
    m : torch.Tensor
        Shape ``(*domain, *shared, *element_shape)``.
    n : torch.Tensor
        Shape ``(*shared, *codomain, *element_shape)``.
    n_contract : int
        Number of shared index axes to contract.

    Returns
    -------
    torch.Tensor
        Shape ``(*domain, *codomain, *element_shape)``.

    Raises
    ------
    ValueError
        If ``n_contract`` is below one, the shared axes differ, or an
        operand lacks the element axes.
    """
    rank = len(self.element_shape)
    m_index = m.ndim - rank
    n_index = n.ndim - rank
    if n_contract < 1:
        raise ValueError(f"n_contract must be >= 1, got {n_contract}")
    if (
        m_index < n_contract
        or n_index < n_contract
        or tuple(m.shape[m_index:]) != self.element_shape
        or tuple(n.shape[n_index:]) != self.element_shape
    ):
        raise ValueError(
            f"operands of shapes {tuple(m.shape)} and {tuple(n.shape)} do "
            f"not hold {n_contract} shared axes of elements of shape "
            f"{self.element_shape}"
        )
    shared_m = m.shape[m_index - n_contract : m_index]
    shared_n = n.shape[:n_contract]
    if shared_m != shared_n:
        raise ValueError(
            f"shared dimensions do not match: "
            f"m trailing {shared_m} != n leading {shared_n}"
        )
    return _composite(self, m, n, n_contract, rank)

Algebra

Bases: CompositionRule, UnitalCarrier

Abstract commutative algebra for V-enriched composition.

An algebra supplies the operations (⊗, ⋁, ⋀, ¬) and the elements I (unit) and ⊥ (zero) on a scalar carrier. Every shipped algebra satisfies I ⊗ a = a, ⊥ ⊗ a = ⊥ and ⋁(a, ⊥) = a, so the identity tensor is a two-sided identity for composition. Associativity of composition is a further property, held exactly by the Semiring subclasses; an Algebra that is not a Semiring (PRODUCT_FUZZY, LUKASIEWICZ, PROBABILITY and their duals) composes with identities but not associatively.

unit and zero are the scalar constants; unit_like and zero_like give them in a requested shape, dtype and device. Subclasses implement the primitive operations and contains.

element_shape property

element_shape: tuple[int, ...]

The empty shape: one element is one entry.

RETURNS DESCRIPTION
tuple of int

().

unit abstractmethod property

unit: float

Unit element I of the monoidal product ⊗.

RETURNS DESCRIPTION
float

The unit.

zero abstractmethod property

zero: float

Bottom element ⊥, the identity of ⋁.

RETURNS DESCRIPTION
float

The zero.

meet abstractmethod

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

Meet ⋀, the reduction for universal quantification (∀).

PARAMETER DESCRIPTION
t

Input tensor with values in L.

TYPE: Tensor

dim

Dimension(s) to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

Reduced tensor.

Source code in src/quivers/core/algebras.py
@abstractmethod
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """Meet ⋀, the reduction for universal quantification (∀).

    Parameters
    ----------
    t : torch.Tensor
        Input tensor with values in L.
    dim : int or tuple of int
        Dimension(s) to reduce.

    Returns
    -------
    torch.Tensor
        Reduced tensor.
    """
    ...

negate abstractmethod

negate(t: Tensor) -> Tensor

Complement / negation ¬.

PARAMETER DESCRIPTION
t

Input tensor.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

¬t, elementwise.

Source code in src/quivers/core/algebras.py
@abstractmethod
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """Complement / negation ¬.

    Parameters
    ----------
    t : torch.Tensor
        Input tensor.

    Returns
    -------
    torch.Tensor
        ¬t, elementwise.
    """
    ...

zero_like

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The zero in a requested shape, dtype and device.

PARAMETER DESCRIPTION
shape

The shape.

TYPE: tuple of int

like

The tensor whose dtype and device the zero takes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A constant tensor holding zero.

RAISES DESCRIPTION
TypeError

If the dtype cannot hold the zero.

Source code in src/quivers/core/algebras.py
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The zero in a requested shape, dtype and device.

    Parameters
    ----------
    shape : tuple of int
        The shape.
    like : torch.Tensor
        The tensor whose dtype and device the zero takes.

    Returns
    -------
    torch.Tensor
        A constant tensor holding ``zero``.

    Raises
    ------
    TypeError
        If the dtype cannot hold the zero.
    """
    return constant(self.zero, tuple(shape), like)

unit_like

unit_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The unit in a requested shape, dtype and device.

PARAMETER DESCRIPTION
shape

The shape.

TYPE: tuple of int

like

The tensor whose dtype and device the unit takes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A constant tensor holding unit.

RAISES DESCRIPTION
TypeError

If the dtype cannot hold the unit.

Source code in src/quivers/core/algebras.py
def unit_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The unit in a requested shape, dtype and device.

    Parameters
    ----------
    shape : tuple of int
        The shape.
    like : torch.Tensor
        The tensor whose dtype and device the unit takes.

    Returns
    -------
    torch.Tensor
        A constant tensor holding ``unit``.

    Raises
    ------
    TypeError
        If the dtype cannot hold the unit.
    """
    return constant(self.unit, tuple(shape), like)

dual

dual() -> Algebra

The role-swapped dual algebra.

The dual uses the base join (as a binary operation) for its tensor_op, the base tensor_op (folded as a reduction) for its join, and swaps unit and zero:

tensor_op^op(a, b) = a ⋁ b
join^op(a_1, ..., a_n) = a_1 ⊗ ... ⊗ a_n
1^op = 0,    0^op = 1.

When ⊗ is a t-norm T and ⋁ is its De Morgan dual t-conorm S(a, b) = N(T(N(a), N(b))) under the strong negation N(a) = 1 - a, the swap exchanges a t-norm with its dual t-conorm. For ProductFuzzyAlgebra this yields the pair (⊗ = probabilistic sum, ⋁ = product reduction).

RETURNS DESCRIPTION
Algebra

The dual. BooleanAlgebra and GodelAlgebra return a DualIdempotentSemiring, since swapping a distributive lattice's join and meet gives a distributive lattice again; every other base returns a DualAlgebra, which need not be a semiring even when the base is one.

Source code in src/quivers/core/algebras.py
def dual(self) -> Algebra:
    """The role-swapped dual algebra.

    The dual uses the base ``join`` (as a binary operation) for its
    ``tensor_op``, the base ``tensor_op`` (folded as a reduction)
    for its ``join``, and swaps ``unit`` and ``zero``:

        tensor_op^op(a, b) = a ⋁ b
        join^op(a_1, ..., a_n) = a_1 ⊗ ... ⊗ a_n
        1^op = 0,    0^op = 1.

    When ``⊗`` is a t-norm ``T`` and ``⋁`` is its De Morgan dual
    t-conorm ``S(a, b) = N(T(N(a), N(b)))`` under the strong negation
    ``N(a) = 1 - a``, the swap exchanges a t-norm with its dual
    t-conorm. For ``ProductFuzzyAlgebra`` this yields the pair
    ``(⊗ = probabilistic sum, ⋁ = product reduction)``.

    Returns
    -------
    Algebra
        The dual. `BooleanAlgebra` and `GodelAlgebra` return a
        `DualIdempotentSemiring`, since swapping a distributive
        lattice's join and meet gives a distributive lattice again;
        every other base returns a `DualAlgebra`, which need not be
        a semiring even when the base is one.
    """
    return DualAlgebra(self)

Semiring

Bases: Algebra, OrderPreservingSemiring

An algebra whose operations form a commutative semiring.

A commutative semiring (L, ⊕, ⊗, 0, 1) has (L, ⊕, 0) and (L, ⊗, 1) commutative monoids, ⊗ distributing over ⊕ on both sides, and 0 annihilating ⊗ [Golan (1999)]. Here ⊕ is the binary form of join, 0 is zero and 1 is unit. These laws make the composition (f >> g)[i, k] = ⊕_j f[i, j] ⊗ g[j, k] associative and unital, so finite sets with tensors over L form a category (the category of L-valued matrices). Membership in this class is a claim that the laws hold; claims reports the status of each, and the law grid of the evidence harness checks every shipped instance.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

IdempotentSemiring

Bases: Semiring

A commutative semiring whose addition is idempotent.

Additive idempotence, a ⊕ a = a for every a, makes ⊕ the join of the partial order a ≤ b ⟺ a ⊕ b = b [Golan (1999)]. On finite carriers of composition this is the structure that a quantale restricts to, and it is what the fuzzy powerset monad needs (see quivers.monadic.monads.FuzzyPowersetMonad). In the shipped instances meet is the infimum of that order and top is its greatest element, so each is a bounded distributive lattice under (join, meet).

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

top abstractmethod property

top: float

The greatest element of the order a ≤ b ⟺ a ⊕ b = b.

It absorbs the join (a ⊕ ⊤ = ⊤) and is the meet of the empty family.

RETURNS DESCRIPTION
float

The top.

residuum abstractmethod

residuum(w: Tensor, x: Tensor) -> Tensor

The residuum [w, x], the greatest v with v ⊗ w ≤ x.

The order is a ≤ b ⟺ a ⊕ b = b. Residuation, v ⊗ w ≤ x ⟺ v ≤ [w, x], makes [w, -] right adjoint to - ⊗ w; it is the internal hom that weighted limits and the Yoneda lemma use.

PARAMETER DESCRIPTION
w

The left argument, broadcastable with x.

TYPE: Tensor

x

The right argument.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

[w, x] elementwise.

Source code in src/quivers/core/algebras.py
@abstractmethod
def residuum(self, w: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
    """The residuum ``[w, x]``, the greatest ``v`` with ``v ⊗ w ≤ x``.

    The order is ``a ≤ b ⟺ a ⊕ b = b``. Residuation,
    ``v ⊗ w ≤ x ⟺ v ≤ [w, x]``, makes ``[w, -]`` right adjoint to
    ``- ⊗ w``; it is the internal hom that weighted limits and
    the Yoneda lemma use.

    Parameters
    ----------
    w : torch.Tensor
        The left argument, broadcastable with ``x``.
    x : torch.Tensor
        The right argument.

    Returns
    -------
    torch.Tensor
        ``[w, x]`` elementwise.
    """
    ...

Selection didactic-model

Selection(*, value: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), witness: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The result of a selective reduction and the operand it selected.

PARAMETER DESCRIPTION
value

The selected operand at every remaining index.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

witness

The flat position of the selected operand in row-major order of the reduced axes, as int64.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

Selective

Bases: Carrier

A carrier whose sum returns one of its operands.

a ⊕ b is a or b: the sum selects the operand that is best under the order rank defines. The tie rule is one for every operation: the first best operand, in row-major order of the reduced axes (a before b in join_pair), is the value's witness and receives the whole derivative. Splitting the derivative over tied operands is another element of the subdifferential; using it in one operation and not in another would make a derivative depend on bracketing.

rank abstractmethod

rank(t: Tensor) -> Tensor

A key whose largest value marks the best operand.

PARAMETER DESCRIPTION
t

Elements of the carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A key of the same shape, strictly increasing in the order the sum selects by.

Source code in src/quivers/core/algebras.py
@abstractmethod
def rank(self, t: torch.Tensor) -> torch.Tensor:
    """A key whose largest value marks the best operand.

    Parameters
    ----------
    t : torch.Tensor
        Elements of the carrier.

    Returns
    -------
    torch.Tensor
        A key of the same shape, strictly increasing in the order the
        sum selects by.
    """
    ...

select

select(t: Tensor, dim: int | tuple[int, ...]) -> Selection

The best operand over index axes and its witness.

PARAMETER DESCRIPTION
t

Elements of the carrier.

TYPE: Tensor

dim

Index axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Selection

The best operand and the flat position of the first one.

RAISES DESCRIPTION
ValueError

If a reduced axis has size zero, since nothing is selected, or the carrier is not scalar.

Source code in src/quivers/core/algebras.py
def select(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> Selection:
    """The best operand over index axes and its witness.

    Parameters
    ----------
    t : torch.Tensor
        Elements of the carrier.
    dim : int or tuple of int
        Index axes to reduce.

    Returns
    -------
    Selection
        The best operand and the flat position of the first one.

    Raises
    ------
    ValueError
        If a reduced axis has size zero, since nothing is selected,
        or the carrier is not scalar.
    """
    if self.element_shape:
        raise ValueError("selection is defined on scalar carriers")
    axes = reduction_axes(t, dim)
    if is_empty(t, axes):
        raise ValueError("a reduction over no terms selects no operand")
    value, witness = _select(t, axes, self.rank(t))
    return Selection(value=value, witness=witness)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The selective sum over index axes.

PARAMETER DESCRIPTION
t

Elements of the carrier.

TYPE: Tensor

dim

Index axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The first best operand at every remaining index, or the zero for a reduction over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The selective sum over index axes.

    Parameters
    ----------
    t : torch.Tensor
        Elements of the carrier.
    dim : int or tuple of int
        Index axes to reduce.

    Returns
    -------
    torch.Tensor
        The first best operand at every remaining index, or the zero
        for a reduction over no terms.
    """
    axes = reduction_axes(t, dim, len(self.element_shape))
    if is_empty(t, axes):
        return self.empty_join(t, axes)
    return self.select(t, axes).value

ZeroSumFree

Bases: Carrier

A carrier in which a sum is zero only when every term is.

With NoZeroDivisors this makes the support map onto the Boolean semiring a homomorphism: a sum is nonzero exactly when some term is [Golan (1999), "zerosumfree"].

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

NoZeroDivisors

Bases: UnitalCarrier

A carrier in which a product is zero only when a factor is.

Golan (1999) calls such a semiring entire. With ZeroSumFree it makes the support map a homomorphism.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

Semifield

Bases: NoZeroDivisors

A carrier in which every element other than zero has an inverse.

divide(a, b) is a ⊗ b⁻¹ for b other than the zero, so (a ⊗ b) ⊘ b = a. A semifield has no zero divisors: if a ⊗ b = 0 and b is not zero then a = (a ⊗ b) ⊘ b = 0. Executors that eliminate by division (directed spanning trees, weight pushing) ask for this capability.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

divide abstractmethod

divide(a: Tensor, b: Tensor) -> Tensor

The quotient a ⊘ b.

PARAMETER DESCRIPTION
a

The dividend.

TYPE: Tensor

b

The divisor, broadcastable with a, with no zero element.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊗ b⁻¹.

RAISES DESCRIPTION
ZeroDivisionError

If an element of b is the zero.

Source code in src/quivers/core/algebras.py
@abstractmethod
def divide(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The quotient ``a ⊘ b``.

    Parameters
    ----------
    a : torch.Tensor
        The dividend.
    b : torch.Tensor
        The divisor, broadcastable with ``a``, with no zero element.

    Returns
    -------
    torch.Tensor
        ``a ⊗ b⁻¹``.

    Raises
    ------
    ZeroDivisionError
        If an element of ``b`` is the zero.
    """
    ...

require_nonzero

require_nonzero(b: Tensor) -> None

Refuse a divisor holding the zero.

PARAMETER DESCRIPTION
b

The divisor.

TYPE: Tensor

RAISES DESCRIPTION
ZeroDivisionError

If an element of b is the zero.

Source code in src/quivers/core/algebras.py
def require_nonzero(self, b: torch.Tensor) -> None:
    """Refuse a divisor holding the zero.

    Parameters
    ----------
    b : torch.Tensor
        The divisor.

    Raises
    ------
    ZeroDivisionError
        If an element of ``b`` is the zero.
    """
    if bool(self.is_zero(b).any()):
        raise ZeroDivisionError(f"division by the zero of {self.name}")

Ring

Bases: Carrier

A carrier whose sum has inverses.

subtract(a, b) is a ⊕ (−b), where −b is the additive inverse, so a ⊕ (0 ⊖ a) = 0. Algorithms that cancel terms, such as a determinant by elimination, need this capability; it gives up the relative accuracy of sums of nonnegative terms.

subtract abstractmethod

subtract(a: Tensor, b: Tensor) -> Tensor

The difference a ⊖ b.

PARAMETER DESCRIPTION
a

The minuend.

TYPE: Tensor

b

The subtrahend, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊕ (−b).

Source code in src/quivers/core/algebras.py
@abstractmethod
def subtract(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The difference ``a ⊖ b``.

    Parameters
    ----------
    a : torch.Tensor
        The minuend.
    b : torch.Tensor
        The subtrahend, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        ``a ⊕ (−b)``.
    """
    ...

Semimodule

Bases: Carrier

A commutative monoid acted on by an order-preserving semiring.

A left semimodule over K is a commutative monoid (M, ⊕, 0) with an action K × M → M that is associative, unital, and distributes over both sums, and in which the zero of either side annihilates [Golan (1999)]. Expectation carriers, whose second component is acted on by probabilities, are built from this capability; FreeSemimodule is the module of vectors over K.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

scalars abstractmethod property

The semiring that acts.

RETURNS DESCRIPTION
OrderPreservingSemiring

The scalars.

act abstractmethod

act(k: Tensor, m: Tensor) -> Tensor

The action k · m.

PARAMETER DESCRIPTION
k

Scalars, with the scalars' element axes trailing.

TYPE: Tensor

m

Module elements with the same index shape (or one that broadcasts with it).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

k · m.

Source code in src/quivers/core/algebras.py
@abstractmethod
def act(self, k: torch.Tensor, m: torch.Tensor) -> torch.Tensor:
    """The action ``k · m``.

    Parameters
    ----------
    k : torch.Tensor
        Scalars, with the scalars' element axes trailing.
    m : torch.Tensor
        Module elements with the same index shape (or one that
        broadcasts with it).

    Returns
    -------
    torch.Tensor
        ``k · m``.
    """
    ...

DivergentClosureError

Bases: ValueError

A path closure has no value in the declared carrier.

UndecidedClosureError

Bases: ValueError

Rounding leaves open whether a path closure converges.

The weight of a cycle lies within the bound on rounding of the value at which its series stops converging, so the computed numbers cannot tell a convergent closure from a divergent one. No value is returned.

ClosureWork didactic-model

ClosureWork(*, pivots: int, sums: int, products: int, exact: int = 0)

Bases: Model

The work of one closure, counted in elements of the algebra.

PARAMETER DESCRIPTION
pivots

States eliminated.

TYPE: int

sums

Binary sums of elements.

TYPE: int

products

Binary products of elements.

TYPE: int

exact

Operations of the exact or enclosed decision of the loops, which runs only when a loop weight lies within the rounding bound of the boundary: rational updates of an entry, or interval updates of an entry. Zero when no loop entered the band.

TYPE: int DEFAULT: 0

RealEmbedding

Bases: Carrier

A carrier embedded in the nonnegative reals.

to_reals maps each element to a nonnegative real so that sums and products are those of the reals and the natural order is that of the reals, and from_reals maps a real of the image back. A monotone polynomial system over such a carrier is one over [0, ∞), whose least fixed point lies in [0, ∞]^n [Etessami and Yannakakis (2009)]; it can be bounded from both sides in interval arithmetic, which certifies it, and the solution is in the carrier exactly when it is finite.

References

Etessami, K., and Yannakakis, M. (2009). Recursive Markov chains, stochastic grammars, and monotone systems of nonlinear equations. Journal of the ACM 56(1), 1-66. doi:10.1145/1462153.1462154

embedding_rounding abstractmethod property

embedding_rounding: int

Units in the last place each map may be off by in float arithmetic.

RETURNS DESCRIPTION
int

Zero for a map computed exactly.

to_reals abstractmethod

to_reals(t: Tensor) -> Tensor

The nonnegative reals of elements.

PARAMETER DESCRIPTION
t

Elements.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Their images, in the dtype of t.

Source code in src/quivers/core/algebras.py
@abstractmethod
def to_reals(self, t: torch.Tensor) -> torch.Tensor:
    """The nonnegative reals of elements.

    Parameters
    ----------
    t : torch.Tensor
        Elements.

    Returns
    -------
    torch.Tensor
        Their images, in the dtype of ``t``.
    """
    ...

from_reals abstractmethod

from_reals(t: Tensor) -> Tensor

The elements of nonnegative reals of the image.

PARAMETER DESCRIPTION
t

Nonnegative reals.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The elements they are the images of.

Source code in src/quivers/core/algebras.py
@abstractmethod
def from_reals(self, t: torch.Tensor) -> torch.Tensor:
    """The elements of nonnegative reals of the image.

    Parameters
    ----------
    t : torch.Tensor
        Nonnegative reals.

    Returns
    -------
    torch.Tensor
        The elements they are the images of.
    """
    ...

Star

Bases: UnitalCarrier

A carrier whose square matrices have a closure.

star(A) is the least solution X of X = I ⊕ A X on the declared domain, the sum I ⊕ A ⊕ A² ⊕ ... of the weights of all paths, including the empty one [Lehmann (1977)]. Outside the domain the series has no value and star raises DivergentClosureError; when rounding cannot decide which side of the boundary a cycle lies on it raises UndecidedClosureError. The shipped closures eliminate one state after another, so they cost n³ operations of the algebra and keep every entry on the autograd graph.

References

Lehmann, D. J. (1977). Algebraic structures for transitive closure. Theoretical Computer Science, 4(1), 59-76. doi:10.1016/0304-3975(77)90056-1

star_domain abstractmethod property

star_domain: str

The matrices whose closure has a value.

RETURNS DESCRIPTION
str

The domain in words.

star_with_work abstractmethod

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The closure A* = I ⊕ A ⊕ A² ⊕ ... of a square matrix, and its work.

PARAMETER DESCRIPTION
matrix

Shape (n, n, *element_shape).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

The closure, of the same shape, and the pivots, sums, products and exact operations it took.

RAISES DESCRIPTION
DivergentClosureError

If the matrix lies outside star_domain.

UndecidedClosureError

If rounding cannot decide whether it lies inside.

Source code in src/quivers/core/algebras.py
@abstractmethod
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The closure ``A* = I ⊕ A ⊕ A² ⊕ ...`` of a square matrix, and its work.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n, *element_shape)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        The closure, of the same shape, and the pivots, sums, products
        and exact operations it took.

    Raises
    ------
    DivergentClosureError
        If the matrix lies outside `star_domain`.
    UndecidedClosureError
        If rounding cannot decide whether it lies inside.
    """
    ...

star

star(matrix: Tensor) -> Tensor

The closure A* = I ⊕ A ⊕ A² ⊕ ... of a square matrix.

PARAMETER DESCRIPTION
matrix

Shape (n, n, *element_shape).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The closure, of the same shape.

RAISES DESCRIPTION
DivergentClosureError

If the matrix lies outside star_domain.

UndecidedClosureError

If rounding cannot decide whether it lies inside.

Source code in src/quivers/core/algebras.py
def star(self, matrix: torch.Tensor) -> torch.Tensor:
    """The closure ``A* = I ⊕ A ⊕ A² ⊕ ...`` of a square matrix.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n, *element_shape)``.

    Returns
    -------
    torch.Tensor
        The closure, of the same shape.

    Raises
    ------
    DivergentClosureError
        If the matrix lies outside `star_domain`.
    UndecidedClosureError
        If rounding cannot decide whether it lies inside.
    """
    return self.star_with_work(matrix)[0]

DualAlgebra

DualAlgebra(base: Algebra, proof: Proved | None = None)

Bases: Algebra

The role-swapped dual of a commutative algebra.

For a t-norm / t-conorm pair (T, S) related by the strong negation N (S(a, b) = N(T(N(a), N(b)))), the dual algebra carries the role-swapped pair:

tensor_op^op = base.join         (as a binary operation)
join^op      = base.tensor_op    (folded as a reduction)
meet^op      = base.join
unit^op      = base.zero
zero^op      = base.unit
negate^op    = base.negate

Concretely for the built-in pairs:

  • PRODUCT_FUZZY.dual(): ⊗ = probabilistic sum (a + b - ab), ⋁ = product reduction (∏ a_i).
  • LUKASIEWICZ.dual(): ⊗ = bounded sum (min(1, a + b)), ⋁ = folded Łukasiewicz t-norm.
  • GODEL.dual(): ⊗ = max, ⋁ = min.
  • BOOLEAN.dual(): ⊗ = OR, ⋁ = AND.

The dual of a semiring need not be a semiring: the dual of PRODUCT_FUZZY composes with identities but not associatively. The Boolean and Gödel duals are distributive lattices with the roles of join and meet exchanged, and are returned as the DualIdempotentSemiring subclass. The carrier is the base's.

PARAMETER DESCRIPTION
base

The algebra whose operations are swapped.

TYPE: Algebra

proof

The argument for the dual's laws about the carrier, given by the base that knows it; without one those laws are assumed.

TYPE: Proved or None DEFAULT: None

Source code in src/quivers/core/algebras.py
def __init__(self, base: Algebra, proof: Proved | None = None) -> None:
    self._base = base
    self._name = f"Dual({base.name})"
    self._proof = proof

base property

base: Algebra

The underlying algebra this is the dual of.

RETURNS DESCRIPTION
Algebra

The base.

name property

name: str

Dual(<base name>).

RETURNS DESCRIPTION
str

The name.

subject property

subject: ClaimSubject

What the dual's claims are about: the dual of its base.

RETURNS DESCRIPTION
ClaimSubject

The qualified class name with the base's name.

unit property

unit: float

The base zero.

RETURNS DESCRIPTION
float

The unit of the dual.

zero property

zero: float

The base unit.

RETURNS DESCRIPTION
float

The zero of the dual.

evidence

evidence(law: Law) -> LawEvidence

The evidence for a law: the base's argument for laws about the carrier.

PARAMETER DESCRIPTION
law

A law the dual claims.

TYPE: Law

RETURNS DESCRIPTION
LawEvidence

The argument given at construction, or what the class declares.

Source code in src/quivers/core/algebras.py
def evidence(self, law: Law) -> LawEvidence:
    """The evidence for a law: the base's argument for laws about the carrier.

    Parameters
    ----------
    law : Law
        A law the dual claims.

    Returns
    -------
    LawEvidence
        The argument given at construction, or what the class declares.
    """
    if law.scope == "carrier":
        if self._proof is not None:
            return self._proof
        return self.assumption("the base gave no argument for its dual")
    return super().evidence(law)

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The base join of two operands, a first.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⋁_base b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The base join of two operands, ``a`` first.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a ⋁_base b``.
    """
    return self._base.join_pair(a, b)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The base product folded over axes.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The fold, or the base unit over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The base product folded over axes.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The fold, or the base unit over no terms.
    """
    axes = reduction_axes(t, dim)
    if is_empty(t, axes):
        return self.empty_join(t, axes)
    return _fold_along_dim(self._base.tensor_op, t, axes)

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The base join, which the dual uses as its meet.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The base join.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The base join, which the dual uses as its meet.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The base join.
    """
    return self._base.join(t, dim=dim)

negate

negate(t: Tensor) -> Tensor

The base negation.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The base negation of t.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The base negation.

    Parameters
    ----------
    t : torch.Tensor
        Operands.

    Returns
    -------
    torch.Tensor
        The base negation of ``t``.
    """
    return self._base.negate(t)

contains

contains(t: Tensor) -> Tensor

Membership in the base carrier.

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The base's membership.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in the base carrier.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        The base's membership.
    """
    return self._base.contains(t)

dual

dual() -> Algebra

The base: taking the dual twice gives it back.

RETURNS DESCRIPTION
Algebra

The base.

Source code in src/quivers/core/algebras.py
def dual(self) -> Algebra:
    """The base: taking the dual twice gives it back.

    Returns
    -------
    Algebra
        The base.
    """
    return self._base

DualIdempotentSemiring

DualIdempotentSemiring(base: Algebra, proof: Proved | None = None)

Bases: DualAlgebra, IdempotentSemiring

The dual of a distributive-lattice algebra.

Returned by BooleanAlgebra.dual and GodelAlgebra.dual. Swapping the join and meet of a distributive lattice yields a distributive lattice, so the dual is again an idempotent commutative semiring: max (or OR) distributes over min (or AND), the unit of max is the bottom and the bottom of the reversed order, the old top, annihilates max.

The constructor takes the parameters of DualAlgebra, whose proof should argue that the base is a bounded distributive lattice under its join and product.

Source code in src/quivers/core/algebras.py
def __init__(self, base: Algebra, proof: Proved | None = None) -> None:
    self._base = base
    self._name = f"Dual({base.name})"
    self._proof = proof

top property

top: float

The greatest element of the join order, the base zero.

RETURNS DESCRIPTION
float

The top.

residuum

residuum(w: Tensor, x: Tensor) -> Tensor

[w, x] = 0 if w ≥ x (real order), else x.

The dual order reverses the reals and its tensor is max, so max(v, w) ≥ x on the reals; its least real solution is 0 when w ≥ x and x otherwise.

PARAMETER DESCRIPTION
w

The left argument.

TYPE: Tensor

x

The right argument.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The residuum.

Source code in src/quivers/core/algebras.py
def residuum(self, w: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
    """``[w, x] = 0`` if ``w ≥ x`` (real order), else ``x``.

    The dual order reverses the reals and its tensor is ``max``, so
    ``max(v, w) ≥ x`` on the reals; its least real solution is
    ``0`` when ``w ≥ x`` and ``x`` otherwise.

    Parameters
    ----------
    w : torch.Tensor
        The left argument.
    x : torch.Tensor
        The right argument.

    Returns
    -------
    torch.Tensor
        The residuum.
    """
    w, x = torch.broadcast_tensors(torch.as_tensor(w, dtype=x.dtype), x)
    return torch.where(w >= x, torch.zeros_like(x), x)

CustomAlgebra

CustomAlgebra(name: str, tensor_op: Callable[[Tensor, Tensor], Tensor], join: Callable[[Tensor, int | tuple[int, ...]], Tensor], unit: float, zero: float, negate: Callable[[Tensor], Tensor] | None = None, meet: Callable[[Tensor, int | tuple[int, ...]], Tensor] | None = None, verify: bool = True, contains: Callable[[Tensor], Tensor] | None = None)

Bases: Algebra

User-defined algebra built from callable operations.

Construct a fresh algebra from the primitive operations as Python functions, rather than subclassing Algebra for each variant.

The constructor only stores the operations; the user is responsible for ensuring they satisfy the algebra axioms (associativity, identity, distributivity of ⊗ over ⋁, de-Morgan duality between ⊗ and ⋁ via negate for involutive lattices), so every law about the carrier is assumed. Basic structural axioms are sanity-checked at construction time against a handful of fixed sample inputs. A join over no terms is the zero whatever join does, and membership is decided by contains when it is given.

The DSL surface algebra name { tensor_op(a, b) = …; join(t) = …; unit = …; zero = …; } compiles to this class under the hood, with verify=False (user expressions are arithmetic and routinely violate one of the canned samples used by _sanity_check).

PARAMETER DESCRIPTION
name

Human-readable name.

TYPE: str

tensor_op

Binary product.

TYPE: Callable

join

Reduction along axes, called on nonempty axes only.

TYPE: Callable

unit

Unit of the product.

TYPE: float

zero

Identity of the join.

TYPE: float

negate

Negation, if any.

TYPE: Callable or None DEFAULT: None

meet

Universal reduction, if any.

TYPE: Callable or None DEFAULT: None

verify

Whether to run the sample checks.

TYPE: bool DEFAULT: True

contains

The carrier's membership predicate, if declared.

TYPE: Callable or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If name is empty or a sample check fails.

Source code in src/quivers/core/algebras.py
def __init__(
    self,
    name: str,
    tensor_op: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
    join: Callable[[torch.Tensor, int | tuple[int, ...]], torch.Tensor],
    unit: float,
    zero: float,
    negate: Callable[[torch.Tensor], torch.Tensor] | None = None,
    meet: (
        Callable[[torch.Tensor, int | tuple[int, ...]], torch.Tensor] | None
    ) = None,
    verify: bool = True,
    contains: Callable[[torch.Tensor], torch.Tensor] | None = None,
) -> None:
    if not name:
        raise ValueError("CustomAlgebra: name must be non-empty")
    self._name = str(name)
    self._tensor_op = tensor_op
    self._join = join
    self._unit = float(unit)
    self._zero = float(zero)
    self._negate = negate
    self._meet = meet
    self._contains = contains
    if verify:
        self._sanity_check()

name property

name: str

The name given at construction.

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

The given unit.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

The given zero.

RETURNS DESCRIPTION
float

The zero.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The given product.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊗ b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The given product.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a ⊗ b``.
    """
    return self._tensor_op(a, b)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The given join, or the zero over no terms.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The reduction.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The given join, or the zero over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The reduction.
    """
    axes = reduction_axes(t, dim)
    if is_empty(t, axes):
        return self.empty_join(t, axes)
    return self._join(t, dim)

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The given meet.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The reduction.

RAISES DESCRIPTION
NotImplementedError

If no meet was given.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The given meet.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The reduction.

    Raises
    ------
    NotImplementedError
        If no meet was given.
    """
    if self._meet is None:
        raise NotImplementedError(
            f"CustomAlgebra {self._name!r}: no meet supplied. "
            f"Pass meet=... to the constructor for explicit "
            f"universal-quantifier support."
        )
    return self._meet(t, dim)

negate

negate(t: Tensor) -> Tensor

The given negation.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

¬t.

RAISES DESCRIPTION
NotImplementedError

If no negation was given.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The given negation.

    Parameters
    ----------
    t : torch.Tensor
        Operands.

    Returns
    -------
    torch.Tensor
        ``¬t``.

    Raises
    ------
    NotImplementedError
        If no negation was given.
    """
    if self._negate is None:
        raise NotImplementedError(
            f"CustomAlgebra {self._name!r}: no negation supplied. "
            f"Pass negate=... to the constructor for explicit "
            f"complement support."
        )
    return self._negate(t)

contains

contains(t: Tensor) -> Tensor

The given membership predicate.

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is in the carrier.

RAISES DESCRIPTION
TypeError

If the entries are complex or no predicate was given.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """The given membership predicate.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is in the carrier.

    Raises
    ------
    TypeError
        If the entries are complex or no predicate was given.
    """
    require_real(t)
    if self._contains is None:
        raise TypeError(
            f"CustomAlgebra {self._name!r}: no carrier declared. Pass "
            f"contains=... to the constructor."
        )
    return self._contains(t)

CustomSemigroupoid

CustomSemigroupoid(name: str, tensor_op: Callable[[Tensor, Tensor], Tensor], join: Callable[[Tensor, int | tuple[int, ...]], Tensor], verify_associative: bool = True)

Bases: Semigroupoid

User-defined Semigroupoid built from callable operations.

Use for composition rules whose composition is associative but which lack an identity element, for instance weighted shortest paths over a semiring without a multiplicative unit. Callers who want a full algebra (with identity, dagger, compact-closed structure) should use CustomAlgebra instead. Associativity of composition is assumed: the optional sample check covers the scalar product only, which does not suffice for it.

PARAMETER DESCRIPTION
name

Human-readable name.

TYPE: str

tensor_op

Binary monoidal product.

TYPE: Callable

join

Reduction along an axis.

TYPE: Callable

verify_associative

When True (default) checks tensor_op is associative on a fixed pseudo-random sample at construction time. Set False to skip the smoke test.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
ValueError

If name is empty, or if verify_associative is set and tensor_op fails the associativity check.

Source code in src/quivers/core/algebras.py
def __init__(
    self,
    name: str,
    tensor_op: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
    join: Callable[[torch.Tensor, int | tuple[int, ...]], torch.Tensor],
    verify_associative: bool = True,
) -> None:
    if not name:
        raise ValueError("CustomSemigroupoid: name must be non-empty")
    self._name = str(name)
    self._tensor_op = tensor_op
    self._join = join
    if verify_associative:
        self._check_associativity()

name property

name: str

The name given at construction.

RETURNS DESCRIPTION
str

The name.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The given product.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊗ b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The given product.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a ⊗ b``.
    """
    return self._tensor_op(a, b)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The given reduction.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The reduction.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The given reduction.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The reduction.
    """
    return self._join(t, dim)

CustomMagmoid

CustomMagmoid(name: str, tensor_op: Callable[[Tensor, Tensor], Tensor], join: Callable[[Tensor, int | tuple[int, ...]], Tensor])

Bases: Magmoid

User-defined Magmoid built from callable operations.

Use for composition rules whose composition is not associative, for instance signed-dot-product or top-k truncating rules. Callers must pin an association order explicitly when chaining; the runtime does not promise that (f >> g) >> h == f >> (g >> h).

No associativity smoke test runs because a magmoid satisfies no law.

PARAMETER DESCRIPTION
name

Human-readable name.

TYPE: str

tensor_op

Binary product (need not be associative).

TYPE: Callable

join

Reduction along an axis.

TYPE: Callable

RAISES DESCRIPTION
ValueError

If name is empty.

Source code in src/quivers/core/algebras.py
def __init__(
    self,
    name: str,
    tensor_op: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
    join: Callable[[torch.Tensor, int | tuple[int, ...]], torch.Tensor],
) -> None:
    if not name:
        raise ValueError("CustomMagmoid: name must be non-empty")
    self._name = str(name)
    self._tensor_op = tensor_op
    self._join = join

name property

name: str

The name given at construction.

RETURNS DESCRIPTION
str

The name.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The given product.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ⊗ b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The given product.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a ⊗ b``.
    """
    return self._tensor_op(a, b)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The given reduction.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The reduction.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The given reduction.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The reduction.
    """
    return self._join(t, dim)

ProductFuzzyAlgebra

Bases: ZeroSumFree, NoZeroDivisors, Algebra

[0,1] with product t-norm and probabilistic sum (noisy-OR).

The product t-norm does not distribute over the probabilistic sum (0.5 · (0.5 ⊕ 0.5) = 0.375 while (0.5 · 0.5) ⊕ (0.5 · 0.5) = 0.4375), so this algebra is not a semiring and composition is unital but not associative: chains of >> depend on their bracketing. The operations are

⊗ = product:      a ⊗ b = a * b
⋁ = noisy-OR:     ⋁_i x_i = 1 - ∏_i (1 - x_i)
⋀ = product:      ⋀_i x_i = ∏_i x_i
¬ = complement:    ¬a = 1 - a
I = 1.0
⊥ = 0.0

A noisy-OR is 0 only when every term is, and a product only when a factor is, so support is a homomorphism from this algebra. The join is computed in log space, with each term below 1 - EPS.

name property

name: str

"ProductFuzzy".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0.

RETURNS DESCRIPTION
float

The zero.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product a b.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The product.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product ``a b``.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        The product.
    """
    return a * b

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

Noisy-OR in log space: 1 - exp(∑ log(1 - t)).

PARAMETER DESCRIPTION
t

Operands in [0, 1].

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The noisy-OR, which is 0 over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """Noisy-OR in log space: ``1 - exp(∑ log(1 - t))``.

    Parameters
    ----------
    t : torch.Tensor
        Operands in ``[0, 1]``.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The noisy-OR, which is 0 over no terms.
    """
    axes = reduction_axes(t, dim)
    if is_empty(t, axes):
        return self.empty_join(t, axes)
    t_clamped = t.clamp(min=0.0, max=1.0 - EPS)
    log_complement = torch.log1p(-t_clamped)
    return -torch.expm1(log_complement.sum(dim=axes))

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The product ∏_i t_i, which is 1 over no terms.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The product.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The product ``∏_i t_i``, which is 1 over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The product.
    """
    return _product(t, dim)

negate

negate(t: Tensor) -> Tensor

The complement 1 - t.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The complement.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The complement ``1 - t``.

    Parameters
    ----------
    t : torch.Tensor
        Operands.

    Returns
    -------
    torch.Tensor
        The complement.
    """
    return 1.0 - t

contains

contains(t: Tensor) -> Tensor

Membership in [0, 1].

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry lies in [0, 1].

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``[0, 1]``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry lies in ``[0, 1]``.
    """
    return _unit_interval(t)

compose

compose(m: Tensor, n: Tensor, n_contract: int) -> Tensor

Composition by a noisy-OR of products, in log space.

PARAMETER DESCRIPTION
m

Left tensor of shape (*domain, *shared).

TYPE: Tensor

n

Right tensor of shape (*shared, *codomain).

TYPE: Tensor

n_contract

Number of shared axes to contract.

TYPE: int

RETURNS DESCRIPTION
Tensor

The composite of shape (*domain, *codomain).

RAISES DESCRIPTION
ValueError

If n_contract is below one or the shared axes differ.

Source code in src/quivers/core/algebras.py
def compose(
    self,
    m: torch.Tensor,
    n: torch.Tensor,
    n_contract: int,
) -> torch.Tensor:
    """Composition by a noisy-OR of products, in log space.

    Parameters
    ----------
    m : torch.Tensor
        Left tensor of shape ``(*domain, *shared)``.
    n : torch.Tensor
        Right tensor of shape ``(*shared, *codomain)``.
    n_contract : int
        Number of shared axes to contract.

    Returns
    -------
    torch.Tensor
        The composite of shape ``(*domain, *codomain)``.

    Raises
    ------
    ValueError
        If ``n_contract`` is below one or the shared axes differ.
    """
    if n_contract < 1:
        raise ValueError(f"n_contract must be >= 1, got {n_contract}")
    shared_m = m.shape[-n_contract:]
    shared_n = n.shape[:n_contract]
    if shared_m != shared_n:
        raise ValueError(
            f"shared dimensions do not match: "
            f"m trailing {shared_m} != n leading {shared_n}"
        )
    n_domain = m.ndim - n_contract
    n_codomain = n.ndim - n_contract
    m_expanded = m.reshape(*m.shape, *([1] * n_codomain))
    n_expanded = n.reshape(*([1] * n_domain), *n.shape)
    product = m_expanded * n_expanded
    product_clamped = product.clamp(min=0.0, max=1.0 - EPS)
    log_complement = torch.log1p(-product_clamped)
    contract_dims = tuple(range(n_domain, n_domain + n_contract))
    return -torch.expm1(log_complement.sum(dim=contract_dims))

dual

dual() -> Algebra

The dual: probabilistic sum as product, product as join.

RETURNS DESCRIPTION
Algebra

A DualAlgebra whose carrier laws are proved.

Source code in src/quivers/core/algebras.py
def dual(self) -> Algebra:
    """The dual: probabilistic sum as product, product as join.

    Returns
    -------
    Algebra
        A `DualAlgebra` whose carrier laws are proved.
    """
    return DualAlgebra(
        self,
        proof=_proved("dual-product-fuzzy"),
    )

BooleanAlgebra

Bases: Selective, Semifield, ZeroSumFree, Star, IdempotentSemiring

{0, 1} with logical AND and OR.

The enrichment for the category Rel of crisp binary relations:

⊗ = AND:     a ⊗ b = a ∧ b
⋁ = OR:      ⋁_i x_i = max_i x_i
⋀ = AND:     ⋀_i x_i = min_i x_i
¬ = NOT:     ¬a = 1 - a
I = 1.0
⊥ = 0.0

The join selects an operand (OR of truth values is their maximum), and 1, the only element other than 0, is its own inverse, so the Boolean semiring is a selective semifield.

star_domain property

star_domain: str

Every matrix: no loop is better than the unit.

RETURNS DESCRIPTION
str

The domain.

name property

name: str

"Boolean".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0, true.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0, false.

RETURNS DESCRIPTION
float

The zero.

top property

top: float

The greatest element of the join order.

RETURNS DESCRIPTION
float

1.0.

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The closure by elimination; every loop weight closes to the unit.

PARAMETER DESCRIPTION
matrix

Shape (n, n).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

A* and the work of the closure.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The closure by elimination; every loop weight closes to the unit.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        ``A*`` and the work of the closure.
    """
    return _eliminate(
        self,
        matrix,
        lambda loop, step: self.unit_like((), loop),
        unit_diagonal=True,
    )

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

Logical AND as a product, exact on {0, 1}.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ∧ b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Logical AND as a product, exact on ``{0, 1}``.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a ∧ b``.
    """
    return a * b

rank

rank(t: Tensor) -> Tensor

The value itself: true is better than false.

PARAMETER DESCRIPTION
t

Truth values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

t.

Source code in src/quivers/core/algebras.py
def rank(self, t: torch.Tensor) -> torch.Tensor:
    """The value itself: true is better than false.

    Parameters
    ----------
    t : torch.Tensor
        Truth values.

    Returns
    -------
    torch.Tensor
        ``t``.
    """
    return t

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

Logical AND as a minimum; true over no terms.

PARAMETER DESCRIPTION
t

Truth values.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The conjunction.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """Logical AND as a minimum; true over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Truth values.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The conjunction.
    """
    return _extremum(
        t, dim, largest=False, empty=_filled(t, dim, self.top), carrier=self.name
    )

negate

negate(t: Tensor) -> Tensor

Logical NOT, 1 - t.

PARAMETER DESCRIPTION
t

Truth values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The negation.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """Logical NOT, ``1 - t``.

    Parameters
    ----------
    t : torch.Tensor
        Truth values.

    Returns
    -------
    torch.Tensor
        The negation.
    """
    return 1.0 - t

divide

divide(a: Tensor, b: Tensor) -> Tensor

a ⊘ 1 = a.

PARAMETER DESCRIPTION
a

The dividend.

TYPE: Tensor

b

The divisor, every element true.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a ∧ b, which is a.

RAISES DESCRIPTION
ZeroDivisionError

If an element of b is false.

Source code in src/quivers/core/algebras.py
def divide(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """``a ⊘ 1 = a``.

    Parameters
    ----------
    a : torch.Tensor
        The dividend.
    b : torch.Tensor
        The divisor, every element true.

    Returns
    -------
    torch.Tensor
        ``a ∧ b``, which is ``a``.

    Raises
    ------
    ZeroDivisionError
        If an element of ``b`` is false.
    """
    self.require_nonzero(b)
    return a * b

contains

contains(t: Tensor) -> Tensor

Membership in {0, 1}.

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is 0 or 1.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``{0, 1}``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is 0 or 1.
    """
    t = _require_carrier(t)
    return (t == 0) | (t == 1)

dual

dual() -> Algebra

The dual algebra, an idempotent commutative semiring.

RETURNS DESCRIPTION
Algebra

A DualIdempotentSemiring over this algebra.

Source code in src/quivers/core/algebras.py
def dual(self) -> Algebra:
    """The dual algebra, an idempotent commutative semiring.

    Returns
    -------
    Algebra
        A `DualIdempotentSemiring` over this algebra.
    """
    return DualIdempotentSemiring(
        self,
        proof=_proved("dual-boolean"),
    )

residuum

residuum(w: Tensor, x: Tensor) -> Tensor

[w, x] = ¬w ∨ x, Boolean implication.

PARAMETER DESCRIPTION
w

The left argument.

TYPE: Tensor

x

The right argument.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The implication.

Source code in src/quivers/core/algebras.py
def residuum(self, w: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
    """``[w, x] = ¬w ∨ x``, Boolean implication.

    Parameters
    ----------
    w : torch.Tensor
        The left argument.
    x : torch.Tensor
        The right argument.

    Returns
    -------
    torch.Tensor
        The implication.
    """
    w, x = torch.broadcast_tensors(torch.as_tensor(w, dtype=x.dtype), x)
    return torch.maximum(1.0 - w, x)

StandardMVAlgebra

Bases: ZeroSumFree, Algebra

The standard MV-algebra on [0, 1].

The standard MV-algebra is [0, 1] with x ⊕ y = min(1, x + y) and ¬x = 1 - x, the real-valued semantics of Łukasiewicz logic [Chang (1958); Cignoli, D'Ottaviano and Mundici (2000)]. Its derived product is the Łukasiewicz t-norm and its lattice meet is min:

⊗ = Łukasiewicz t-norm:  a ⊗ b = max(a + b - 1, 0)
⋁ = bounded sum:         ⋁_i x_i = min(1, ∑_i x_i)
⋀ = min:                 ⋀_i x_i = min_i x_i
¬ = strong negation:     ¬a = 1 - a
I = 1.0
⊥ = 0.0

The Łukasiewicz t-norm does not distribute over the bounded sum (0.5 ⊗ (0.5 ⊕ 0.5) = 0.5 while (0.5 ⊗ 0.5) ⊕ (0.5 ⊗ 0.5) = 0), so this algebra is not a semiring and composition depends on its bracketing. The product has zero divisors (0.5 ⊗ 0.5 = 0), so support is not a homomorphism from it. The name follows the standard terminology: a "Łukasiewicz algebra" in the literature is Moisil's distinct Łukasiewicz-Moisil algebra.

References

Chang, C. C. (1958). Algebraic analysis of many valued logics. Transactions of the American Mathematical Society, 88(2), 467-490. doi:10.1090/S0002-9947-1958-0094302-9

Cignoli, R. L. O., D'Ottaviano, I. M. L., and Mundici, D. (2000). Algebraic Foundations of Many-Valued Reasoning. Springer. doi:10.1007/978-94-015-9480-6

name property

name: str

"Lukasiewicz".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0.

RETURNS DESCRIPTION
float

The zero.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The Łukasiewicz t-norm max(a + b - 1, 0).

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The t-norm.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The Łukasiewicz t-norm ``max(a + b - 1, 0)``.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        The t-norm.
    """
    return (a + b - 1.0).clamp(min=0.0)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The bounded sum min(1, ∑_i t_i).

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The bounded sum, which is 0 over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The bounded sum ``min(1, ∑_i t_i)``.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The bounded sum, which is 0 over no terms.
    """
    return _sum(t, dim).clamp(max=1.0)

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The minimum, which is 1 over no terms.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The minimum.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The minimum, which is 1 over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The minimum.
    """
    return _extremum(
        t, dim, largest=False, empty=_filled(t, dim, 1.0), carrier=self.name
    )

negate

negate(t: Tensor) -> Tensor

The strong negation 1 - t.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The negation.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The strong negation ``1 - t``.

    Parameters
    ----------
    t : torch.Tensor
        Operands.

    Returns
    -------
    torch.Tensor
        The negation.
    """
    return 1.0 - t

contains

contains(t: Tensor) -> Tensor

Membership in [0, 1].

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry lies in [0, 1].

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``[0, 1]``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry lies in ``[0, 1]``.
    """
    return _unit_interval(t)

dual

dual() -> Algebra

The dual: bounded sum as product, t-norm as join.

RETURNS DESCRIPTION
Algebra

A DualAlgebra whose carrier laws are proved.

Source code in src/quivers/core/algebras.py
def dual(self) -> Algebra:
    """The dual: bounded sum as product, t-norm as join.

    Returns
    -------
    Algebra
        A `DualAlgebra` whose carrier laws are proved.
    """
    return DualAlgebra(
        self,
        proof=_proved("dual-lukasiewicz"),
    )

GodelAlgebra

Bases: Selective, ZeroSumFree, NoZeroDivisors, Star, IdempotentSemiring

[0,1] with Gödel (min) t-norm.

⊗ = min, ⋁ = max, ⋀ = min, ¬ = Gödel neg (1 if a == 0 else 0), I = 1.0, ⊥ = 0.0.

The join selects the larger operand.

star_domain property

star_domain: str

Every matrix: no loop is better than the unit.

RETURNS DESCRIPTION
str

The domain.

name property

name: str

"Godel".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0.

RETURNS DESCRIPTION
float

The zero.

top property

top: float

The greatest element of the join order.

RETURNS DESCRIPTION
float

1.0.

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The closure by elimination; every loop weight closes to the unit.

PARAMETER DESCRIPTION
matrix

Shape (n, n).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

A* and the work of the closure.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The closure by elimination; every loop weight closes to the unit.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        ``A*`` and the work of the closure.
    """
    return _eliminate(
        self,
        matrix,
        lambda loop, step: self.unit_like((), loop),
        unit_diagonal=True,
    )

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The minimum, the Gödel t-norm.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

min(a, b).

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The minimum, the Gödel t-norm.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``min(a, b)``.
    """
    return torch.min(a, b)

rank

rank(t: Tensor) -> Tensor

The value itself: larger is better.

PARAMETER DESCRIPTION
t

Elements.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

t.

Source code in src/quivers/core/algebras.py
def rank(self, t: torch.Tensor) -> torch.Tensor:
    """The value itself: larger is better.

    Parameters
    ----------
    t : torch.Tensor
        Elements.

    Returns
    -------
    torch.Tensor
        ``t``.
    """
    return t

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The minimum; the top over no terms.

PARAMETER DESCRIPTION
t

Elements.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The minimum.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The minimum; the top over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Elements.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The minimum.
    """
    return _extremum(
        t, dim, largest=False, empty=_filled(t, dim, self.top), carrier=self.name
    )

negate

negate(t: Tensor) -> Tensor

The Gödel negation: 1 at 0, else 0.

PARAMETER DESCRIPTION
t

Elements.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The negation, in the dtype of t.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The Gödel negation: 1 at 0, else 0.

    Parameters
    ----------
    t : torch.Tensor
        Elements.

    Returns
    -------
    torch.Tensor
        The negation, in the dtype of ``t``.
    """
    return (t == 0).to(dtype=t.dtype)

contains

contains(t: Tensor) -> Tensor

Membership in [0, 1].

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry lies in [0, 1].

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``[0, 1]``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry lies in ``[0, 1]``.
    """
    return _unit_interval(t)

dual

dual() -> Algebra

The dual algebra, an idempotent commutative semiring.

RETURNS DESCRIPTION
Algebra

A DualIdempotentSemiring over this algebra.

Source code in src/quivers/core/algebras.py
def dual(self) -> Algebra:
    """The dual algebra, an idempotent commutative semiring.

    Returns
    -------
    Algebra
        A `DualIdempotentSemiring` over this algebra.
    """
    return DualIdempotentSemiring(
        self,
        proof=_proved("dual-godel"),
    )

residuum

residuum(w: Tensor, x: Tensor) -> Tensor

[w, x] = 1 if w ≤ x, else x: the Gödel implication.

PARAMETER DESCRIPTION
w

The left argument.

TYPE: Tensor

x

The right argument.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The implication.

Source code in src/quivers/core/algebras.py
def residuum(self, w: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
    """``[w, x] = 1`` if ``w ≤ x``, else ``x``: the Gödel implication.

    Parameters
    ----------
    w : torch.Tensor
        The left argument.
    x : torch.Tensor
        The right argument.

    Returns
    -------
    torch.Tensor
        The implication.
    """
    w, x = torch.broadcast_tensors(torch.as_tensor(w, dtype=x.dtype), x)
    return torch.where(w <= x, torch.ones_like(x), x)

TropicalAlgebra

Bases: Selective, ZeroSumFree, NoZeroDivisors, Star, IdempotentSemiring

[0, ∞] with (+, min), the enrichment of Lawvere metric spaces.

⊗ = addition (distances compose),
⋁ = infimum (shortest path),
⋀ = supremum (longest path),
I = 0.0, ⊥ = ∞.

Composition is the tropical / (min, +) matrix product. The join selects the smaller operand. Negation is undefined. The carrier has no negative numbers, so an element other than 0 has no inverse and the algebra is not a semifield.

star_domain property

star_domain: str

Every matrix: no distance is shorter than zero.

RETURNS DESCRIPTION
str

The domain.

name property

name: str

"Tropical".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

0.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

∞.

RETURNS DESCRIPTION
float

The zero.

top property

top: float

The greatest element of the join order.

RETURNS DESCRIPTION
float

0.0.

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The closure by elimination; every loop weight closes to the unit.

PARAMETER DESCRIPTION
matrix

Shape (n, n).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

A* and the work of the closure.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The closure by elimination; every loop weight closes to the unit.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        ``A*`` and the work of the closure.
    """
    return _eliminate(
        self,
        matrix,
        lambda loop, step: self.unit_like((), loop),
        unit_diagonal=True,
    )

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

Addition of distances.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a + b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Addition of distances.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a + b``.
    """
    return a + b

rank

rank(t: Tensor) -> Tensor

The negated value: shorter is better.

PARAMETER DESCRIPTION
t

Distances.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

-t.

Source code in src/quivers/core/algebras.py
def rank(self, t: torch.Tensor) -> torch.Tensor:
    """The negated value: shorter is better.

    Parameters
    ----------
    t : torch.Tensor
        Distances.

    Returns
    -------
    torch.Tensor
        ``-t``.
    """
    return -t

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The supremum of distances; the top 0 over no terms.

PARAMETER DESCRIPTION
t

Distances.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The maximum.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The supremum of distances; the top 0 over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Distances.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The maximum.
    """
    return _extremum(
        t, dim, largest=True, empty=_filled(t, dim, self.top), carrier=self.name
    )

negate

negate(t: Tensor) -> Tensor

Refuse: negation is not defined here.

PARAMETER DESCRIPTION
t

Distances.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Never returns.

RAISES DESCRIPTION
NotImplementedError

Always.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """Refuse: negation is not defined here.

    Parameters
    ----------
    t : torch.Tensor
        Distances.

    Returns
    -------
    torch.Tensor
        Never returns.

    Raises
    ------
    NotImplementedError
        Always.
    """
    raise NotImplementedError(
        "negation is not well-defined for the tropical algebra"
    )

contains

contains(t: Tensor) -> Tensor

Membership in [0, ∞].

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is nonnegative or infinite.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``[0, ∞]``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is nonnegative or infinite.
    """
    t = _require_carrier(t)
    return t >= 0

residuum

residuum(w: Tensor, x: Tensor) -> Tensor

[w, x] = max(x - w, 0), truncated subtraction.

The order reverses the reals (a ≤ b ⟺ min(a, b) = b), so v + w ≤ x there means v + w ≥ x on the reals, whose least real solution is max(x - w, 0); w = ∞ gives 0.

PARAMETER DESCRIPTION
w

The left argument.

TYPE: Tensor

x

The right argument.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The residuum.

Source code in src/quivers/core/algebras.py
def residuum(self, w: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
    """``[w, x] = max(x - w, 0)``, truncated subtraction.

    The order reverses the reals (``a ≤ b ⟺ min(a, b) = b``), so
    ``v + w ≤ x`` there means ``v + w ≥ x`` on the reals, whose
    least real solution is ``max(x - w, 0)``; ``w = ∞`` gives ``0``.

    Parameters
    ----------
    w : torch.Tensor
        The left argument.
    x : torch.Tensor
        The right argument.

    Returns
    -------
    torch.Tensor
        The residuum.
    """
    w, x = torch.broadcast_tensors(torch.as_tensor(w, dtype=x.dtype), x)
    diff = torch.where(torch.isinf(w), torch.zeros_like(x), x - w)
    return diff.clamp(min=0.0)

MaxPlusAlgebra

Bases: Selective, Semifield, ZeroSumFree, Star, IdempotentSemiring

Max-plus (Viterbi) semifield on ℝ ∪ {-∞}.

Distinct from TropicalAlgebra (which is min-plus, suited to shortest-path aggregations): the join here is max and the tensor is +. The canonical algebra for MAP decoding in HMMs, CRFs, and weighted automata.

⊗ = +,   ⋁ = max,   ⋀ = min,
I = 0, ⊥ = -∞.

The join selects the larger operand, and every finite score a has the inverse -a. top and the residuum live in the completion ℝ ∪ {±∞}; +∞ is not in the semiring's carrier, where -∞ must annihilate.

star_domain property

star_domain: str

The matrices without a cycle of positive score.

RETURNS DESCRIPTION
str

The domain.

name property

name: str

"MaxPlus".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

0.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

-∞.

RETURNS DESCRIPTION
float

The zero.

top property

top: float

The greatest element of the completed order.

RETURNS DESCRIPTION
float

+∞.

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The best path scores, by elimination with a decided loop test.

A computed loop score above the rounding bound of its path proves a positive cycle, and one below minus the bound proves the loop is not positive. In between, the sign of the exact sum of the float64 or float32 weights decides: the cycles are tested in exact rational arithmetic on the given weights.

PARAMETER DESCRIPTION
matrix

Shape (n, n).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

A* and the work of the closure.

RAISES DESCRIPTION
DivergentClosureError

If a cycle has positive score.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The best path scores, by elimination with a decided loop test.

    A computed loop score above the rounding bound of its path proves
    a positive cycle, and one below minus the bound proves the loop is
    not positive. In between, the sign of the exact sum of the
    float64 or float32 weights decides: the cycles are tested in
    exact rational arithmetic on the given weights.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        ``A*`` and the work of the closure.

    Raises
    ------
    DivergentClosureError
        If a cycle has positive score.
    """
    _square(matrix)
    largest = _largest_finite(matrix)
    verdict: list[bool] = []

    def repeat(loop: torch.Tensor, step: int) -> torch.Tensor:
        """The closure of one loop score.

        Parameters
        ----------
        loop : torch.Tensor
            The loop score.
        step : int
            The states eliminated before it.

        Returns
        -------
        torch.Tensor
            The unit, when the loop does not gain.

        Raises
        ------
        DivergentClosureError
            If a cycle has positive score.
        """
        # A loop met after ``step`` eliminations is a sum of at most
        # ``2 step + 1`` entries, rounded at most ``2 step`` times.
        bound = _rounding(loop.dtype, 2 * step) * (2 * step + 1) * largest
        gains = float(loop) > bound
        if not gains and float(loop) >= -bound:
            if not verdict:
                verdict.append(_positive_cycle(matrix))
            gains = verdict[0]
        if gains:
            raise DivergentClosureError(
                "the best-path closure diverges: a cycle has positive score, "
                "so a path around it can be made arbitrarily heavy"
            )
        return self.unit_like((), loop)

    star, work = _eliminate(self, matrix, repeat, unit_diagonal=True)
    return star, work.with_(exact=matrix.shape[0] ** 3 if verdict else 0)

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

Addition of scores.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a + b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Addition of scores.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a + b``.
    """
    return a + b

rank

rank(t: Tensor) -> Tensor

The value itself: larger is better.

PARAMETER DESCRIPTION
t

Scores.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

t.

Source code in src/quivers/core/algebras.py
def rank(self, t: torch.Tensor) -> torch.Tensor:
    """The value itself: larger is better.

    Parameters
    ----------
    t : torch.Tensor
        Scores.

    Returns
    -------
    torch.Tensor
        ``t``.
    """
    return t

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The minimum; the top +∞ of the completion over no terms.

PARAMETER DESCRIPTION
t

Scores.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The minimum.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The minimum; the top ``+∞`` of the completion over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Scores.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The minimum.
    """
    return _extremum(
        t, dim, largest=False, empty=_filled(t, dim, self.top), carrier=self.name
    )

negate

negate(t: Tensor) -> Tensor

Refuse: negation is not defined here.

PARAMETER DESCRIPTION
t

Scores.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Never returns.

RAISES DESCRIPTION
NotImplementedError

Always.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """Refuse: negation is not defined here.

    Parameters
    ----------
    t : torch.Tensor
        Scores.

    Returns
    -------
    torch.Tensor
        Never returns.

    Raises
    ------
    NotImplementedError
        Always.
    """
    raise NotImplementedError(
        "negation is not well-defined for the max-plus algebra"
    )

divide

divide(a: Tensor, b: Tensor) -> Tensor

The quotient a - b.

PARAMETER DESCRIPTION
a

The dividend.

TYPE: Tensor

b

The divisor, every element finite.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a - b.

RAISES DESCRIPTION
ZeroDivisionError

If an element of b is -∞.

Source code in src/quivers/core/algebras.py
def divide(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The quotient ``a - b``.

    Parameters
    ----------
    a : torch.Tensor
        The dividend.
    b : torch.Tensor
        The divisor, every element finite.

    Returns
    -------
    torch.Tensor
        ``a - b``.

    Raises
    ------
    ZeroDivisionError
        If an element of ``b`` is ``-∞``.
    """
    self.require_nonzero(b)
    return a - b

contains

contains(t: Tensor) -> Tensor

Membership in ℝ ∪ {-∞}.

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is finite or -∞.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``ℝ ∪ {-∞}``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is finite or ``-∞``.
    """
    return _extended_below(t)

residuum

residuum(w: Tensor, x: Tensor) -> Tensor

[w, x] = x - w, with [-∞, x] = +∞ and [w, +∞] = +∞.

PARAMETER DESCRIPTION
w

The left argument.

TYPE: Tensor

x

The right argument.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The residuum.

Source code in src/quivers/core/algebras.py
def residuum(self, w: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
    """``[w, x] = x - w``, with ``[-∞, x] = +∞`` and ``[w, +∞] = +∞``.

    Parameters
    ----------
    w : torch.Tensor
        The left argument.
    x : torch.Tensor
        The right argument.

    Returns
    -------
    torch.Tensor
        The residuum.
    """
    w, x = torch.broadcast_tensors(torch.as_tensor(w, dtype=x.dtype), x)
    inf = torch.full_like(x, float("inf"))
    out = torch.where(torch.isneginf(w), inf, x - w)
    return torch.where(torch.isposinf(x), inf, out)

LogProbAlgebra

Bases: Semifield, ZeroSumFree, Star, RealEmbedding, Semiring

Log-space sum-product semifield on [-∞, ∞).

Tensor is real addition (probability multiplication in log- space) and join is torch.logsumexp (probability summation in log-space). exp is an isomorphism onto the probability semiring ([0, ∞), +, ·), so the carrier must contain positive values: logsumexp(0, 0) = log 2. The join is not idempotent, so this is a semiring and not a lattice. Division is subtraction of log weights.

⊗ = +,   ⋁ = logsumexp,   ⋀ = min,
I = 0 (log 1), ⊥ = -∞ (log 0).

A join of terms that are all -∞ is -∞ with derivative zero: the log of a sum of absent alternatives is -∞ near them, so no mass moves. The binary sum agrees with the join over the pair in value and in first and second derivatives at every point; its derivative is not torch.logaddexp's, whose second derivative is not a number at an operand -∞. The meet has no value over no terms, since the carrier has no greatest element.

embedding_rounding property

embedding_rounding: int

The rounding of exp and log that the certificates assume.

RETURNS DESCRIPTION
int

Two units in the last place; the law grid checks it on its samples against arithmetic in fifty digits.

star_domain property

star_domain: str

The matrices of probabilities whose spectral radius is below one.

RETURNS DESCRIPTION
str

The domain.

name property

name: str

"LogProb".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

0.0, the log of one.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

-∞, the log of zero.

RETURNS DESCRIPTION
float

The zero.

to_reals

to_reals(t: Tensor) -> Tensor

The probabilities of log weights.

PARAMETER DESCRIPTION
t

Log weights.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

exp(t), zero at -∞.

Source code in src/quivers/core/algebras.py
def to_reals(self, t: torch.Tensor) -> torch.Tensor:
    """The probabilities of log weights.

    Parameters
    ----------
    t : torch.Tensor
        Log weights.

    Returns
    -------
    torch.Tensor
        ``exp(t)``, zero at ``-∞``.
    """
    return torch.exp(t)

from_reals

from_reals(t: Tensor) -> Tensor

The log weights of probabilities.

PARAMETER DESCRIPTION
t

Nonnegative reals.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

log(t), -∞ at zero.

Source code in src/quivers/core/algebras.py
def from_reals(self, t: torch.Tensor) -> torch.Tensor:
    """The log weights of probabilities.

    Parameters
    ----------
    t : torch.Tensor
        Nonnegative reals.

    Returns
    -------
    torch.Tensor
        ``log(t)``, ``-∞`` at zero.
    """
    return torch.log(t)

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The log of (I - A)⁻¹, by elimination of states in log space.

PARAMETER DESCRIPTION
matrix

Shape (n, n), -∞ for absent edges.

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

Log weights of all paths, including empty paths, and the work.

RAISES DESCRIPTION
DivergentClosureError

If an effective return weight is at least one.

UndecidedClosureError

If convergence or a usable pivot cannot be established in the working precision.

ValueError

If the matrix contains NaN or positive infinity.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The log of ``(I - A)⁻¹``, by elimination of states in log space.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n)``, ``-∞`` for absent edges.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        Log weights of all paths, including empty paths, and the work.

    Raises
    ------
    DivergentClosureError
        If an effective return weight is at least one.
    UndecidedClosureError
        If convergence or a usable pivot cannot be established in the
        working precision.
    ValueError
        If the matrix contains NaN or positive infinity.
    """
    _square(matrix)
    demand(
        ~(torch.isnan(matrix) | torch.isposinf(matrix)),
        lambda: ValueError(
            "log closure requires finite weights or negative infinity"
        ),
    )
    largest = _largest_finite(matrix)
    verdicts = _Verdicts(
        lambda: _log_verdicts(matrix), _elimination_cost(_square(matrix))
    )

    def repeat(loop: torch.Tensor, step: int) -> torch.Tensor:
        """The log of ``1 / (1 - e^loop)``.

        Parameters
        ----------
        loop : torch.Tensor
            The log loop weight.
        step : int
            The states eliminated before it.

        Returns
        -------
        torch.Tensor
            The log closure of the loop.
        """
        # Each eliminated state rounds a log-sum and the log of a
        # geometric series, at most sixteen roundings of a log weight no
        # larger than the sum of ``2 step + 1`` entries.
        bound = _rounding(loop.dtype, 16 * step) * max(
            1.0, (2 * step + 1) * largest
        )
        _decide(
            loop,
            step,
            loop >= bound,
            loop < -bound,
            verdicts,
            "an effective return weight is at least one",
        )
        denominator = -torch.expm1(loop)
        # A float64 enclosure can establish convergence even when
        # float32 elimination rounds this effective return weight to
        # one. That certificate does not make the working pivot usable.
        demand(
            denominator > 0,
            lambda: UndecidedClosureError(
                "the working precision cannot evaluate a convergent log closure pivot"
            ),
        )
        return -torch.log(denominator)

    star, work = _eliminate(self, matrix, repeat)
    return star, work.with_(exact=verdicts.operations)

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

Addition of log weights.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a + b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Addition of log weights.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a + b``.
    """
    return a + b

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The log of a sum of exponentials, stable and with zero masked.

PARAMETER DESCRIPTION
t

Log weights.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The reduction with the named axes removed. A reduction over no terms, or over terms that are all -∞, is -∞ with derivative zero.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The log of a sum of exponentials, stable and with zero masked.

    Parameters
    ----------
    t : torch.Tensor
        Log weights.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The reduction with the named axes removed. A reduction over
        no terms, or over terms that are all ``-∞``, is ``-∞`` with
        derivative zero.
    """
    axes = reduction_axes(t, dim)
    if is_empty(t, axes):
        return self.empty_join(t, axes)
    # ``torch.logsumexp`` has the right value for an all-``-inf``
    # reduction but differentiates that value as ``NaN``. Impossible
    # dynamic-programming cells are represented by exactly such rows, so
    # the impossible rows are replaced by zeros before the reduction and
    # their result is a constant. Replacing them before the reduction
    # is essential: masking the result afterwards leaves the ``NaN`` of
    # the reduction in the autograd graph.
    impossible = torch.isneginf(t).all(dim=axes, keepdim=True)
    safe = torch.where(impossible, torch.zeros_like(t), t)
    total = torch.logsumexp(safe, dim=axes)
    return torch.where(
        impossible.squeeze(axes), torch.full_like(total, -float("inf")), total
    )

join_pair

join_pair(a: Tensor, b: Tensor) -> Tensor

The binary sum log(e^a + e^b), equal to join over the pair.

PARAMETER DESCRIPTION
a

The first log weight.

TYPE: Tensor

b

The second log weight, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The sum. It agrees with join over the pair in value and in its first and second derivatives at every point: two absent operands give -∞ with zero derivatives, and one gives the other's derivatives exactly.

Source code in src/quivers/core/algebras.py
def join_pair(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The binary sum ``log(e^a + e^b)``, equal to `join` over the pair.

    Parameters
    ----------
    a : torch.Tensor
        The first log weight.
    b : torch.Tensor
        The second log weight, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        The sum. It agrees with `join` over the pair in value and in
        its first and second derivatives at every point: two absent
        operands give ``-∞`` with zero derivatives, and one gives the
        other's derivatives exactly.
    """
    a, b = torch.broadcast_tensors(a, b)
    impossible = torch.isneginf(a) & torch.isneginf(b)
    zero = torch.zeros_like(a)
    total = _LogSumPair.apply(
        torch.where(impossible, zero, a), torch.where(impossible, zero, b)
    )
    return torch.where(impossible, torch.full_like(total, -float("inf")), total)

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The minimum, refused over no terms.

PARAMETER DESCRIPTION
t

Log weights.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The minimum.

RAISES DESCRIPTION
ValueError

If a reduced axis has size zero.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The minimum, refused over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Log weights.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The minimum.

    Raises
    ------
    ValueError
        If a reduced axis has size zero.
    """
    return _extremum(t, dim, largest=False, empty=None, carrier=self.name)

negate

negate(t: Tensor) -> Tensor

Refuse: negation is not defined here.

PARAMETER DESCRIPTION
t

Log weights.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Never returns.

RAISES DESCRIPTION
NotImplementedError

Always.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """Refuse: negation is not defined here.

    Parameters
    ----------
    t : torch.Tensor
        Log weights.

    Returns
    -------
    torch.Tensor
        Never returns.

    Raises
    ------
    NotImplementedError
        Always.
    """
    raise NotImplementedError(
        "negation is not well-defined for the log-prob algebra"
    )

divide

divide(a: Tensor, b: Tensor) -> Tensor

The quotient a - b of log weights.

PARAMETER DESCRIPTION
a

The dividend.

TYPE: Tensor

b

The divisor, every element finite.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a - b.

RAISES DESCRIPTION
ZeroDivisionError

If an element of b is -∞.

Source code in src/quivers/core/algebras.py
def divide(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The quotient ``a - b`` of log weights.

    Parameters
    ----------
    a : torch.Tensor
        The dividend.
    b : torch.Tensor
        The divisor, every element finite.

    Returns
    -------
    torch.Tensor
        ``a - b``.

    Raises
    ------
    ZeroDivisionError
        If an element of ``b`` is ``-∞``.
    """
    self.require_nonzero(b)
    return a - b

contains

contains(t: Tensor) -> Tensor

Membership in [-∞, ∞).

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is finite or -∞.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``[-∞, ∞)``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is finite or ``-∞``.
    """
    return _extended_below(t)

RealAlgebra

Bases: Semifield, Ring, Semiring

The field of real numbers (ℝ, +, ·).

The canonical numeric semiring: addition is the semiring sum (not a lattice join, since it is not idempotent), multiplication the tensor. Use when entries are unbounded real weights with no probability interpretation. Subtraction and division are available, and sums may cancel, so support is not a homomorphism from it.

name property

name: str

"Real".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0.

RETURNS DESCRIPTION
float

The zero.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product a b.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The product.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product ``a b``.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        The product.
    """
    return a * b

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The sum over axes.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The sum, which is 0 over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The sum over axes.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The sum, which is 0 over no terms.
    """
    axes = reduction_axes(t, dim)
    result = t
    for d in reversed(axes):
        result = result.sum(dim=d)
    return result

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The minimum, refused over no terms.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The minimum.

RAISES DESCRIPTION
ValueError

If a reduced axis has size zero.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The minimum, refused over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The minimum.

    Raises
    ------
    ValueError
        If a reduced axis has size zero.
    """
    return _extremum(t, dim, largest=False, empty=None, carrier=self.name)

negate

negate(t: Tensor) -> Tensor

The additive inverse -t.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

-t.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The additive inverse ``-t``.

    Parameters
    ----------
    t : torch.Tensor
        Operands.

    Returns
    -------
    torch.Tensor
        ``-t``.
    """
    return -t

subtract

subtract(a: Tensor, b: Tensor) -> Tensor

The difference a - b.

PARAMETER DESCRIPTION
a

The minuend.

TYPE: Tensor

b

The subtrahend.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a - b.

Source code in src/quivers/core/algebras.py
def subtract(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The difference ``a - b``.

    Parameters
    ----------
    a : torch.Tensor
        The minuend.
    b : torch.Tensor
        The subtrahend.

    Returns
    -------
    torch.Tensor
        ``a - b``.
    """
    return a - b

divide

divide(a: Tensor, b: Tensor) -> Tensor

The quotient a / b.

PARAMETER DESCRIPTION
a

The dividend.

TYPE: Tensor

b

The divisor, with no zero element.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a / b.

RAISES DESCRIPTION
ZeroDivisionError

If an element of b is 0.

Source code in src/quivers/core/algebras.py
def divide(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The quotient ``a / b``.

    Parameters
    ----------
    a : torch.Tensor
        The dividend.
    b : torch.Tensor
        The divisor, with no zero element.

    Returns
    -------
    torch.Tensor
        ``a / b``.

    Raises
    ------
    ZeroDivisionError
        If an element of ``b`` is 0.
    """
    self.require_nonzero(b)
    return a / b

contains

contains(t: Tensor) -> Tensor

Membership in ℝ.

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is finite.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``ℝ``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is finite.
    """
    t = _require_carrier(t)
    return torch.isfinite(t)

BoundedSumProductAlgebra

Bases: ZeroSumFree, NoZeroDivisors, Algebra

[0, 1] with the product t-norm and the bounded sum.

The tensor is the product t-norm a · b and the join is the bounded sum min(1, ∑_i x_i), the Łukasiewicz t-conorm [Klement, Mesiar and Pap (2000)]. Truncating the sum at 1 breaks distributivity (0.5 · min(1, 1 + 1) = 0.5 while min(1, 0.5 + 0.5) over the products is 1), so this algebra is not a semiring and composition depends on its bracketing. The probability semiring ([0, ∞), +, ·) is MarkovAlgebra; this class is not a probability algebra in the measure-theoretic sense (a Boolean algebra carrying a measure) either.

References

Klement, E. P., Mesiar, R., and Pap, E. (2000). Triangular Norms. Springer. doi:10.1007/978-94-015-9540-7

name property

name: str

"Probability".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0.

RETURNS DESCRIPTION
float

The zero.

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product, clamped to [0, 1].

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The product.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product, clamped to ``[0, 1]``.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        The product.
    """
    return (a * b).clamp(min=0.0, max=1.0)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The bounded sum min(1, ∑_i t_i).

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The bounded sum, which is 0 over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The bounded sum ``min(1, ∑_i t_i)``.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The bounded sum, which is 0 over no terms.
    """
    return _sum(t, dim).clamp(min=0.0, max=1.0)

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The minimum, which is 1 over no terms.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The minimum.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The minimum, which is 1 over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The minimum.
    """
    return _extremum(
        t, dim, largest=False, empty=_filled(t, dim, 1.0), carrier=self.name
    )

negate

negate(t: Tensor) -> Tensor

The complement 1 - t, clamped to [0, 1].

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The complement.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The complement ``1 - t``, clamped to ``[0, 1]``.

    Parameters
    ----------
    t : torch.Tensor
        Operands.

    Returns
    -------
    torch.Tensor
        The complement.
    """
    return (1.0 - t).clamp(min=0.0, max=1.0)

contains

contains(t: Tensor) -> Tensor

Membership in [0, 1].

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry lies in [0, 1].

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``[0, 1]``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry lies in ``[0, 1]``.
    """
    return _unit_interval(t)

CountingAlgebra

Bases: ZeroSumFree, NoZeroDivisors, Star, Semiring

Sum-product semiring on the non-negative integers (ℕ, +, ·).

Counting algebra: composition counts the number of distinct paths through a structure. Tensors may be floating (autograd requires it) or integer; either way the entries must be natural numbers. The naturals have no inverses, so this is not a semifield; the nonnegative reals are MarkovAlgebra.

star_domain property

star_domain: str

The matrices of counts without a cycle.

RETURNS DESCRIPTION
str

The domain.

name property

name: str

"Counting".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0.

RETURNS DESCRIPTION
float

The zero.

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The number of paths, by elimination of states.

Counts below 2 / eps of the dtype are exact in floating point and elimination only adds and multiplies them, so a loop count is decided exactly.

PARAMETER DESCRIPTION
matrix

Shape (n, n).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

A* and the work of the closure.

RAISES DESCRIPTION
DivergentClosureError

If a cycle has a nonzero count.

UndecidedClosureError

If a count reaches 2 / eps, beyond which it is not exact.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The number of paths, by elimination of states.

    Counts below ``2 / eps`` of the dtype are exact in floating point and elimination only adds and multiplies them, so
    a loop count is decided exactly.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        ``A*`` and the work of the closure.

    Raises
    ------
    DivergentClosureError
        If a cycle has a nonzero count.
    UndecidedClosureError
        If a count reaches ``2 / eps``, beyond which it is not exact.
    """
    star, work = _linear_star(self, matrix, 0)
    if star.is_floating_point():
        limit = 2.0 / torch.finfo(star.dtype).eps
        demand(
            star.detach() < limit,
            lambda: UndecidedClosureError(
                f"a count of paths reaches {limit:.0f}, beyond which it is not "
                "exact"
            ),
        )
    return star, work

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product of counts.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a b.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product of counts.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        ``a b``.
    """
    return a * b

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The sum of counts.

PARAMETER DESCRIPTION
t

Counts.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The sum, which is 0 over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The sum of counts.

    Parameters
    ----------
    t : torch.Tensor
        Counts.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The sum, which is 0 over no terms.
    """
    axes = reduction_axes(t, dim)
    result = t
    for d in reversed(axes):
        result = result.sum(dim=d)
    return result

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The minimum, refused over no terms.

PARAMETER DESCRIPTION
t

Counts.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The minimum.

RAISES DESCRIPTION
ValueError

If a reduced axis has size zero.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The minimum, refused over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Counts.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The minimum.

    Raises
    ------
    ValueError
        If a reduced axis has size zero.
    """
    return _extremum(t, dim, largest=False, empty=None, carrier=self.name)

negate

negate(t: Tensor) -> Tensor

Refuse: negation is not defined here.

PARAMETER DESCRIPTION
t

Counts.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Never returns.

RAISES DESCRIPTION
NotImplementedError

Always.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """Refuse: negation is not defined here.

    Parameters
    ----------
    t : torch.Tensor
        Counts.

    Returns
    -------
    torch.Tensor
        Never returns.

    Raises
    ------
    NotImplementedError
        Always.
    """
    raise NotImplementedError(
        "negation is not well-defined for the counting "
        "(non-negative integer) algebra"
    )

contains

contains(t: Tensor) -> Tensor

Membership in ℕ.

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is a finite nonnegative integer.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``ℕ``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is a finite nonnegative integer.
    """
    valid = _nonnegative(t)
    if t.is_floating_point():
        valid = valid & (t == t.floor())
    return valid

MarkovAlgebra

Bases: Semifield, ZeroSumFree, Star, RealEmbedding, Semiring

Sum-product composition for stochastic matrices.

Implements the composition rule of FinStoch:

(g ∘ f)(a, c) = Σ_b f(a, b) · g(b, c)

standard matrix multiplication on row-stochastic matrices. Formally:

⊗ = product,   ⋁ = sum,   ⋀ = product,
¬ = complement (1 - p),
I = 1.0, ⊥ = 0.0.

The operations form the probability semifield ([0, ∞), +, ·); its sum is not idempotent, so it is a semiring and not a lattice. Composition is ordinary matrix multiplication, and the composite of row-stochastic matrices is row-stochastic.

embedding_rounding property

embedding_rounding: int

The rounding of the identity.

RETURNS DESCRIPTION
int

Zero.

star_domain property

star_domain: str

The nonnegative matrices of spectral radius below one.

RETURNS DESCRIPTION
str

The domain.

name property

name: str

"Markov".

RETURNS DESCRIPTION
str

The name.

unit property

unit: float

1.0.

RETURNS DESCRIPTION
float

The unit.

zero property

zero: float

0.0.

RETURNS DESCRIPTION
float

The zero.

to_reals

to_reals(t: Tensor) -> Tensor

The reals of elements, which are reals.

PARAMETER DESCRIPTION
t

Elements.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

t.

Source code in src/quivers/core/algebras.py
def to_reals(self, t: torch.Tensor) -> torch.Tensor:
    """The reals of elements, which are reals.

    Parameters
    ----------
    t : torch.Tensor
        Elements.

    Returns
    -------
    torch.Tensor
        ``t``.
    """
    return t

from_reals

from_reals(t: Tensor) -> Tensor

The elements of reals, which are themselves.

PARAMETER DESCRIPTION
t

Nonnegative reals.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

t.

Source code in src/quivers/core/algebras.py
def from_reals(self, t: torch.Tensor) -> torch.Tensor:
    """The elements of reals, which are themselves.

    Parameters
    ----------
    t : torch.Tensor
        Nonnegative reals.

    Returns
    -------
    torch.Tensor
        ``t``.
    """
    return t

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

(I - A)⁻¹ by elimination of states, without subtraction.

PARAMETER DESCRIPTION
matrix

Shape (n, n).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

A* and the work of the closure.

RAISES DESCRIPTION
DivergentClosureError

If the spectral radius is at least one.

UndecidedClosureError

If a loop weight is within the rounding bound of one.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """``(I - A)⁻¹`` by elimination of states, without subtraction.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        ``A*`` and the work of the closure.

    Raises
    ------
    DivergentClosureError
        If the spectral radius is at least one.
    UndecidedClosureError
        If a loop weight is within the rounding bound of one.
    """
    return _linear_star(self, matrix, 4)

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product a b.

PARAMETER DESCRIPTION
a

Left operand.

TYPE: Tensor

b

Right operand.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The product.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product ``a b``.

    Parameters
    ----------
    a : torch.Tensor
        Left operand.
    b : torch.Tensor
        Right operand.

    Returns
    -------
    torch.Tensor
        The product.
    """
    return a * b

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The sum over axes.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The sum, which is 0 over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The sum over axes.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The sum, which is 0 over no terms.
    """
    return _sum(t, dim)

meet

meet(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The product over axes, which is 1 over no terms.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

dim

Axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The product.

Source code in src/quivers/core/algebras.py
def meet(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The product over axes, which is 1 over no terms.

    Parameters
    ----------
    t : torch.Tensor
        Operands.
    dim : int or tuple of int
        Axes to reduce.

    Returns
    -------
    torch.Tensor
        The product.
    """
    return _product(t, dim)

negate

negate(t: Tensor) -> Tensor

The complement 1 - t.

PARAMETER DESCRIPTION
t

Operands.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The complement.

Source code in src/quivers/core/algebras.py
def negate(self, t: torch.Tensor) -> torch.Tensor:
    """The complement ``1 - t``.

    Parameters
    ----------
    t : torch.Tensor
        Operands.

    Returns
    -------
    torch.Tensor
        The complement.
    """
    return 1.0 - t

divide

divide(a: Tensor, b: Tensor) -> Tensor

The quotient a / b.

PARAMETER DESCRIPTION
a

The dividend.

TYPE: Tensor

b

The divisor, with no zero element.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

a / b.

RAISES DESCRIPTION
ZeroDivisionError

If an element of b is 0.

Source code in src/quivers/core/algebras.py
def divide(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The quotient ``a / b``.

    Parameters
    ----------
    a : torch.Tensor
        The dividend.
    b : torch.Tensor
        The divisor, with no zero element.

    Returns
    -------
    torch.Tensor
        ``a / b``.

    Raises
    ------
    ZeroDivisionError
        If an element of ``b`` is 0.
    """
    self.require_nonzero(b)
    return a / b

contains

contains(t: Tensor) -> Tensor

Membership in [0, ∞).

PARAMETER DESCRIPTION
t

Entries.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Whether each entry is finite and nonnegative.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Membership in ``[0, ∞)``.

    Parameters
    ----------
    t : torch.Tensor
        Entries.

    Returns
    -------
    torch.Tensor
        Whether each entry is finite and nonnegative.
    """
    return _nonnegative(t)

MatrixSemiring

MatrixSemiring(base: OrderPreservingSemiring, size: int)

Bases: OrderPreservingSemiring

Square matrices over a scalar semiring, a semiring that does not commute.

An element is an n × n matrix over base. The sum is the entrywise sum, the product the matrix product of base, the zero the zero matrix, and the unit the identity matrix. Matrices over a semiring form a semiring [Golan (1999)], and for n ≥ 2 its product does not commute, so a computation over these weights has to keep the order of its factors.

PARAMETER DESCRIPTION
base

The scalar semiring of the entries.

TYPE: OrderPreservingSemiring

size

The order n of the matrices.

TYPE: int

RAISES DESCRIPTION
ValueError

If base is not scalar or size is negative.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

Source code in src/quivers/core/algebras.py
def __init__(self, base: OrderPreservingSemiring, size: int) -> None:
    if base.element_shape != ():
        raise ValueError("matrix entries are scalars of the base")
    if size < 0:
        raise ValueError(f"the order of a matrix is nonnegative, got {size}")
    self._base = base
    self._size = int(size)

base property

The scalar semiring of the entries.

RETURNS DESCRIPTION
OrderPreservingSemiring

The base.

size property

size: int

The order of the matrices.

RETURNS DESCRIPTION
int

n.

name property

name: str

Matrix(<base>, <n>).

RETURNS DESCRIPTION
str

The name.

element_shape property

element_shape: tuple[int, ...]

(n, n).

RETURNS DESCRIPTION
tuple of int

The shape of one matrix.

subject property

subject: ClaimSubject

What the claims are about: the construction over its base.

RETURNS DESCRIPTION
ClaimSubject

The qualified class name with the structure's name.

evidence

evidence(law: Law) -> LawEvidence

The evidence for a law; laws about the carrier hold by a theorem.

PARAMETER DESCRIPTION
law

A law the structure claims.

TYPE: Law

RETURNS DESCRIPTION
LawEvidence

The theorem's argument when the base's laws are established.

Source code in src/quivers/core/algebras.py
def evidence(self, law: Law) -> LawEvidence:
    """The evidence for a law; laws about the carrier hold by a theorem.

    Parameters
    ----------
    law : Law
        A law the structure claims.

    Returns
    -------
    LawEvidence
        The theorem's argument when the base's laws are established.
    """
    if law.scope == "carrier":
        return _inherited(self, self._base, "matrix")
    return super().evidence(law)

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The matrix product a b over the base, a on the left.

PARAMETER DESCRIPTION
a

Left matrices.

TYPE: Tensor

b

Right matrices, broadcastable over index axes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

(a b)[i, k] = ⊕_j a[i, j] ⊗ b[j, k].

RAISES DESCRIPTION
ValueError

If an operand lacks the matrix axes.

Source code in src/quivers/core/algebras.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The matrix product ``a b`` over the base, ``a`` on the left.

    Parameters
    ----------
    a : torch.Tensor
        Left matrices.
    b : torch.Tensor
        Right matrices, broadcastable over index axes.

    Returns
    -------
    torch.Tensor
        ``(a b)[i, k] = ⊕_j a[i, j] ⊗ b[j, k]``.

    Raises
    ------
    ValueError
        If an operand lacks the matrix axes.
    """
    self._check(a)
    self._check(b)
    products = self._base.tensor_op(a.unsqueeze(-1), b.unsqueeze(-3))
    return self._base.join(products, -2)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The entrywise sum over index axes.

PARAMETER DESCRIPTION
t

Matrices.

TYPE: Tensor

dim

Index axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The sum, which is the zero matrix over no terms.

RAISES DESCRIPTION
ValueError

If t lacks the matrix axes.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The entrywise sum over index axes.

    Parameters
    ----------
    t : torch.Tensor
        Matrices.
    dim : int or tuple of int
        Index axes to reduce.

    Returns
    -------
    torch.Tensor
        The sum, which is the zero matrix over no terms.

    Raises
    ------
    ValueError
        If ``t`` lacks the matrix axes.
    """
    self._check(t)
    axes = reduction_axes(t, dim, 2)
    if is_empty(t, axes):
        return self.empty_join(t, axes)
    return self._base.join(t, axes)

zero_like

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The zero matrix at every index.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Shape (*shape, n, n).

Source code in src/quivers/core/algebras.py
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The zero matrix at every index.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        Shape ``(*shape, n, n)``.
    """
    return self._base.zero_like((*shape, *self.element_shape), like)

unit_like

unit_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The identity matrix at every index.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Shape (*shape, n, n).

Source code in src/quivers/core/algebras.py
def unit_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The identity matrix at every index.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        Shape ``(*shape, n, n)``.
    """
    full = (*shape, *self.element_shape)
    diagonal = torch.eye(self._size, dtype=torch.bool, device=like.device)
    return torch.where(
        diagonal,
        self._base.unit_like(full, like),
        self._base.zero_like(full, like),
    )

contains

contains(t: Tensor) -> Tensor

Whether every entry of each matrix is in the base carrier.

PARAMETER DESCRIPTION
t

Matrices.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One truth value per matrix.

RAISES DESCRIPTION
ValueError

If t lacks the matrix axes.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Whether every entry of each matrix is in the base carrier.

    Parameters
    ----------
    t : torch.Tensor
        Matrices.

    Returns
    -------
    torch.Tensor
        One truth value per matrix.

    Raises
    ------
    ValueError
        If ``t`` lacks the matrix axes.
    """
    self._check(t)
    return self._base.contains(t).all(dim=-1).all(dim=-1)

StarMatrixSemiring

StarMatrixSemiring(base: OrderPreservingSemiring, size: int)

Bases: MatrixSemiring, Star

Square matrices over a semiring with a closure, closed as one flat matrix.

MatrixSemiring returns this class when its base is a Star. An n × n matrix A whose entries are k × k matrices is the nk × nk matrix φ(A)[(i, a), (j, b)] = A[i, j][a, b] of the base, and φ is an isomorphism of semirings from M_n(M_k(S)) onto M_nk(S). The closure of A is therefore φ⁻¹(star(φ(A))): it exists exactly when the base's closure of the flat matrix does, and it is the least solution of X = I ⊕ A X because φ maps solutions to solutions and preserves the order of sums. This is the first closure whose product does not commute; it solves both X = I ⊕ A X and X = I ⊕ X A.

PARAMETER DESCRIPTION
base

The scalar semiring of the entries, which has a closure.

TYPE: OrderPreservingSemiring

size

The order k of the blocks.

TYPE: int

RAISES DESCRIPTION
TypeError

If the base has no closure.

Source code in src/quivers/core/algebras.py
def __init__(self, base: OrderPreservingSemiring, size: int) -> None:
    if not isinstance(base, Star):
        raise TypeError(f"{base!r} has no closure, so its matrices have none")
    super().__init__(base, size)

star_domain property

star_domain: str

The matrices whose flat matrix lies in the base's closure domain.

RETURNS DESCRIPTION
str

The domain.

star_with_work

star_with_work(matrix: Tensor) -> tuple[Tensor, ClosureWork]

The closure of a matrix of blocks, through its flat matrix.

PARAMETER DESCRIPTION
matrix

Shape (n, n, k, k).

TYPE: Tensor

RETURNS DESCRIPTION
tuple of (torch.Tensor, ClosureWork)

A*, of the same shape, and the base's work on the flat matrix.

RAISES DESCRIPTION
DivergentClosureError

If the base's closure of the flat matrix diverges.

UndecidedClosureError

If rounding cannot decide it.

ValueError

If the matrix is not square in its blocks.

Source code in src/quivers/core/algebras.py
def star_with_work(self, matrix: torch.Tensor) -> tuple[torch.Tensor, ClosureWork]:
    """The closure of a matrix of blocks, through its flat matrix.

    Parameters
    ----------
    matrix : torch.Tensor
        Shape ``(n, n, k, k)``.

    Returns
    -------
    tuple of (torch.Tensor, ClosureWork)
        ``A*``, of the same shape, and the base's work on the flat matrix.

    Raises
    ------
    DivergentClosureError
        If the base's closure of the flat matrix diverges.
    UndecidedClosureError
        If rounding cannot decide it.
    ValueError
        If the matrix is not square in its blocks.
    """
    self._check(matrix)
    if matrix.dim() != 4 or matrix.shape[0] != matrix.shape[1]:
        raise ValueError(
            f"a closure needs a square matrix of blocks; got shape {tuple(matrix.shape)}"
        )
    base = self._base
    assert isinstance(base, Star)
    n, k = matrix.shape[0], self._size
    flat = matrix.permute(0, 2, 1, 3).reshape(n * k, n * k)
    closed, work = base.star_with_work(flat)
    return closed.reshape(n, k, n, k).permute(0, 2, 1, 3), work

FreeSemimodule

FreeSemimodule(scalars: OrderPreservingSemiring, size: int)

Bases: Semimodule

Vectors of a fixed length over an order-preserving semiring.

An element is a vector of n scalars. The sum is entrywise, the zero is the zero vector, and a scalar acts on the left of every entry. These operations make K^n a left semimodule over K [Golan (1999)].

PARAMETER DESCRIPTION
scalars

The semiring that acts.

TYPE: OrderPreservingSemiring

size

The length n of the vectors.

TYPE: int

RAISES DESCRIPTION
ValueError

If size is negative.

References

Golan, J. S. (1999). Semirings and their Applications. Springer. doi:10.1007/978-94-015-9333-5

Source code in src/quivers/core/algebras.py
def __init__(self, scalars: OrderPreservingSemiring, size: int) -> None:
    if size < 0:
        raise ValueError(f"the length of a vector is nonnegative, got {size}")
    self._scalars = scalars
    self._size = int(size)

scalars property

The semiring that acts.

RETURNS DESCRIPTION
OrderPreservingSemiring

The scalars.

size property

size: int

The length of the vectors.

RETURNS DESCRIPTION
int

n.

name property

name: str

<scalars>^<n>.

RETURNS DESCRIPTION
str

The name.

element_shape property

element_shape: tuple[int, ...]

(n, *scalars.element_shape).

RETURNS DESCRIPTION
tuple of int

The shape of one vector.

subject property

subject: ClaimSubject

What the claims are about: the construction over its base.

RETURNS DESCRIPTION
ClaimSubject

The qualified class name with the structure's name.

evidence

evidence(law: Law) -> LawEvidence

The evidence for a law; laws about the carrier hold by a theorem.

PARAMETER DESCRIPTION
law

A law the structure claims.

TYPE: Law

RETURNS DESCRIPTION
LawEvidence

The theorem's argument when the base's laws are established.

Source code in src/quivers/core/algebras.py
def evidence(self, law: Law) -> LawEvidence:
    """The evidence for a law; laws about the carrier hold by a theorem.

    Parameters
    ----------
    law : Law
        A law the structure claims.

    Returns
    -------
    LawEvidence
        The theorem's argument when the base's laws are established.
    """
    if law.scope == "carrier":
        return _inherited(self, self._scalars, "free-semimodule")
    return super().evidence(law)

join

join(t: Tensor, dim: int | tuple[int, ...]) -> Tensor

The entrywise sum over index axes.

PARAMETER DESCRIPTION
t

Vectors.

TYPE: Tensor

dim

Index axes to reduce.

TYPE: int or tuple of int

RETURNS DESCRIPTION
Tensor

The sum, which is the zero vector over no terms.

Source code in src/quivers/core/algebras.py
def join(self, t: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
    """The entrywise sum over index axes.

    Parameters
    ----------
    t : torch.Tensor
        Vectors.
    dim : int or tuple of int
        Index axes to reduce.

    Returns
    -------
    torch.Tensor
        The sum, which is the zero vector over no terms.
    """
    axes = reduction_axes(t, dim, len(self.element_shape))
    if is_empty(t, axes):
        return self.empty_join(t, axes)
    return self._scalars.join(t, axes)

act

act(k: Tensor, m: Tensor) -> Tensor

The scalar k on the left of every entry of m.

PARAMETER DESCRIPTION
k

Scalars, with the scalars' element axes trailing.

TYPE: Tensor

m

Vectors.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

(k ⊗ m_1, ..., k ⊗ m_n).

Source code in src/quivers/core/algebras.py
def act(self, k: torch.Tensor, m: torch.Tensor) -> torch.Tensor:
    """The scalar ``k`` on the left of every entry of ``m``.

    Parameters
    ----------
    k : torch.Tensor
        Scalars, with the scalars' element axes trailing.
    m : torch.Tensor
        Vectors.

    Returns
    -------
    torch.Tensor
        ``(k ⊗ m_1, ..., k ⊗ m_n)``.
    """
    rank = len(self._scalars.element_shape)
    return self._scalars.tensor_op(k.unsqueeze(k.ndim - rank), m)

zero_like

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The zero vector at every index.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Shape (*shape, *element_shape).

Source code in src/quivers/core/algebras.py
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The zero vector at every index.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        Shape ``(*shape, *element_shape)``.
    """
    return self._scalars.zero_like((*shape, self._size), like)

contains

contains(t: Tensor) -> Tensor

Whether every entry of each vector is a scalar.

PARAMETER DESCRIPTION
t

Vectors.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One truth value per vector.

Source code in src/quivers/core/algebras.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Whether every entry of each vector is a scalar.

    Parameters
    ----------
    t : torch.Tensor
        Vectors.

    Returns
    -------
    torch.Tensor
        One truth value per vector.
    """
    return self._scalars.contains(t).all(dim=-1)

semigroupoid

semigroupoid(name: str, tensor_op: Callable[[Tensor, Tensor], Tensor], join: Callable[[Tensor, int | tuple[int, ...]], Tensor], *, verify_associative: bool = True) -> CustomSemigroupoid

Convenience constructor for CustomSemigroupoid.

PARAMETER DESCRIPTION
name

Human-readable name.

TYPE: str

tensor_op

Binary monoidal product.

TYPE: Callable

join

Reduction along an axis.

TYPE: Callable

verify_associative

When True (default), smoke-tests tensor_op for associativity on a fixed sample.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
CustomSemigroupoid

The composition rule built from the callables.

RAISES DESCRIPTION
ValueError

If name is empty, or if verify_associative is set and tensor_op fails the associativity check.

Source code in src/quivers/core/algebras.py
def semigroupoid(
    name: str,
    tensor_op: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
    join: Callable[[torch.Tensor, int | tuple[int, ...]], torch.Tensor],
    *,
    verify_associative: bool = True,
) -> CustomSemigroupoid:
    """Convenience constructor for `CustomSemigroupoid`.

    Parameters
    ----------
    name : str
        Human-readable name.
    tensor_op : Callable
        Binary monoidal product.
    join : Callable
        Reduction along an axis.
    verify_associative : bool
        When ``True`` (default), smoke-tests ``tensor_op`` for
        associativity on a fixed sample.

    Returns
    -------
    CustomSemigroupoid
        The composition rule built from the callables.

    Raises
    ------
    ValueError
        If ``name`` is empty, or if ``verify_associative`` is set and
        ``tensor_op`` fails the associativity check.
    """
    return CustomSemigroupoid(
        name, tensor_op, join, verify_associative=verify_associative
    )

magmoid

magmoid(name: str, tensor_op: Callable[[Tensor, Tensor], Tensor], join: Callable[[Tensor, int | tuple[int, ...]], Tensor]) -> CustomMagmoid

Convenience constructor for CustomMagmoid.

PARAMETER DESCRIPTION
name

Human-readable name.

TYPE: str

tensor_op

Binary product, which need not be associative.

TYPE: Callable

join

Reduction along an axis.

TYPE: Callable

RETURNS DESCRIPTION
CustomMagmoid

The composition rule built from the callables.

RAISES DESCRIPTION
ValueError

If name is empty.

Source code in src/quivers/core/algebras.py
def magmoid(
    name: str,
    tensor_op: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
    join: Callable[[torch.Tensor, int | tuple[int, ...]], torch.Tensor],
) -> CustomMagmoid:
    """Convenience constructor for `CustomMagmoid`.

    Parameters
    ----------
    name : str
        Human-readable name.
    tensor_op : Callable
        Binary product, which need not be associative.
    join : Callable
        Reduction along an axis.

    Returns
    -------
    CustomMagmoid
        The composition rule built from the callables.

    Raises
    ------
    ValueError
        If ``name`` is empty.
    """
    return CustomMagmoid(name, tensor_op, join)

material_implication

material_implication() -> CustomMagmoid

Reichenbach material-implication composition as a Magmoid.

The tensor product is the Reichenbach implication a → b = 1 - a + a*b and the join is the product reduction, so (f >> g)[i, k] = ∏_j (1 - f[i, j] + f[i, j] g[j, k]). Neither the scalar implication nor this composition is associative, and no element is a two-sided identity, so the rule is a magmoid.

RETURNS DESCRIPTION
CustomMagmoid

The material-implication composition rule.

Source code in src/quivers/core/algebras.py
def material_implication() -> CustomMagmoid:
    """Reichenbach material-implication composition as a `Magmoid`.

    The tensor product is the Reichenbach implication
    ``a → b = 1 - a + a*b`` and the join is the product reduction, so
    ``(f >> g)[i, k] = ∏_j (1 - f[i, j] + f[i, j] g[j, k])``. Neither
    the scalar implication nor this composition is associative, and
    no element is a two-sided identity, so the rule is a magmoid.

    Returns
    -------
    CustomMagmoid
        The material-implication composition rule.
    """
    return CustomMagmoid("MaterialImplication", _implication, _product)

The algebra singletons, such as PRODUCT_FUZZY, are documented on the core overview.

Cited sources

Joshua Goodman. Semiring Parsing. Computational Linguistics, 25(4):573–606, 1999. URL: https://aclanthology.org/J99-4004/.

Mehryar Mohri. Semiring Frameworks and Algorithms for Shortest-Distance Problems. Journal of Automata, Languages and Combinatorics, 7(3):321–350, 2002. doi:10.25596/jalc-2002-321.

Erich Peter Klement, Radko Mesiar, and Endre Pap. Triangular Norms. Trends in Logic. Springer, 2000. doi:10.1007/978-94-015-9540-7.

G. M. Kelly. Basic Concepts of Enriched Category Theory. Cambridge University Press, 1982. Reprinted in Reprints in Theory and Applications of Categories 10 (2005), 1–136. URL: https://www.tac.mta.ca/tac/reprints/articles/10/tr10abs.html.