Skip to content

Transformations

A transformation rewrites a morphism's entries into another Algebra. An entrywise map (CarrierMap), such as a logarithm, acts on each entry alone. A MorphismTransformation, such as softmax or L1 row normalization, reads a whole row. compose_trans builds sequences of both, and Morphism.change_base applies them. An entrywise map that preserves \(\otimes\), \(\oplus\), and their units commutes with composition, and then applying it is a change of base (Kelly, 1982).

SupportMap is an algebra homomorphism from its declared nonnegative source carriers to Boolean values. It uses strict positivity, validates carrier membership, and preserves the two combining operations and their identities.

algebra_morphisms

Carrier maps, algebra homomorphisms, and change of base for morphisms.

A morphism in quivers.core.morphisms has entries in the carrier of its algebra V. Two morphisms over different algebras do not compose (Morphism.__rshift__ raises incompatible algebras); f.change_base(φ) moves a morphism to another algebra by applying a map φ between the carriers to every entry.

  • CarrierMap is the abstract base: a source algebra, a target algebra, and an entrywise map apply. It promises no law, so change of base along it is an entrywise transformation and need not preserve composition.
  • AlgebraHomomorphism is a carrier map that preserves the algebra's operations: φ(a ⊗ b) = φ(a) ⊗ φ(b), φ(a ⊕ b) = φ(a) ⊕ φ(b), φ(1) = 1 and φ(0) = 0. Between semirings this is a semiring homomorphism [Golan (1999)], and change of base along it is a functor between the categories of matrices: (f >> g).change_base(φ) = f.change_base(φ) >> g.change_base(φ).

The shipped homomorphisms are IdentityHom, Embedding (of a sub-algebra such as BOOLEAN ↪ PRODUCT_FUZZY), CountingToReal, and SupportMap on every source that establishes zero-sum-freeness and the absence of zero divisors. Every other shipped map (MarkovToProductFuzzy, LogProb, MaxPlus, Threshold, ProductFuzzyToGodel, ProbabilityClamp, CountingFromReal, ProbabilityToReal) is a CarrierMap that fails at least one of those equations; the test suite records a counterexample for each.

A registry CARRIER_MAP_REGISTRY keyed by (source.name, target.name) lets the compiler and user code look up the shipped map between two algebras.

References

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

CarrierMap

Bases: ABC

An entrywise map from one algebra's carrier to another's.

A carrier map promises no law: change of base along it applies the map to every entry and need not preserve composition or identities. AlgebraHomomorphism is the subclass whose maps preserve the algebra operations.

source abstractmethod property

source: Algebra

The source algebra V.

target abstractmethod property

target: Algebra

The target algebra W.

name property

name: str

The class name.

RETURNS DESCRIPTION
str

The name of the map.

apply abstractmethod

apply(t: Tensor) -> Tensor

Map a tensor with entries in source.L to a tensor with entries in target.L.

The shape is preserved; only the per-entry lattice changes.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries.

Source code in src/quivers/core/algebra_morphisms.py
@abstractmethod
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Map a tensor with entries in ``source.L`` to a tensor
    with entries in ``target.L``.

    The shape is preserved; only the per-entry lattice changes.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries.
    """

AlgebraHomomorphism

Bases: CarrierMap

A carrier map that preserves the algebra operations.

φ(a ⊗ b) = φ(a) ⊗ φ(b), φ(⋁ a_i) = ⋁ φ(a_i), φ(I) = I and φ(⊥) = ⊥ on the source carrier. Between semirings this is a semiring homomorphism [Golan (1999)], so change of base along it commutes with composition and sends identities to identities. Membership is a claim that the equations hold; the test suite checks every shipped instance.

SupportMap

SupportMap(source: Algebra)

Bases: AlgebraHomomorphism

Map each entry other than the zero to true and the zero to false.

In an algebra that is ZeroSumFree and has NoZeroDivisors, a sum is the zero exactly when every term is, and a product exactly when a factor is. Support therefore preserves the join, the product, the zero and the unit on the mathematical carrier, which is what makes it a homomorphism onto the Boolean algebra [Golan (1999)]. The source is accepted by its capabilities, not by its type: it must establish both laws, by an argument or a decision procedure (see Lawful.establishes), so a subclass that replaces an operation without its own proof is refused. Floating-point products can still underflow to the zero.

Entrywise support preserves binary matrix composition and identities, so for a Semiring source it is a functor between matrix categories. ProductFuzzy and Probability are not semirings, and their matrix composition is not associative. The test for the zero is not differentiable.

PARAMETER DESCRIPTION
source

An algebra that establishes zero-sum-freeness and the absence of zero divisors.

TYPE: Algebra

RAISES DESCRIPTION
TypeError

If the source does not establish both laws.

References

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

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self, source: Algebra) -> None:
    if not (
        isinstance(source, ZeroSumFree)
        and isinstance(source, NoZeroDivisors)
        and source.establishes(ZERO_SUM_FREE, NO_ZERO_DIVISORS)
    ):
        raise TypeError(
            f"support is not a declared homomorphism for {source!r}: the "
            "source must establish zero-sum-freeness and the absence of "
            "zero divisors"
        )
    self._source = source

source property

source: Algebra

The algebra whose entries other than the zero map to true.

RETURNS DESCRIPTION
Algebra

The source.

target property

target: Algebra

The Boolean algebra.

RETURNS DESCRIPTION
Algebra

BOOLEAN.

apply

apply(t: Tensor) -> Tensor

Return the Boolean support of a tensor in the source carrier.

PARAMETER DESCRIPTION
t

Entries in the source algebra's carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Zero-one entries of the same shape, dtype and device.

RAISES DESCRIPTION
TypeError

If entries are complex.

ValueError

If entries lie outside the source carrier.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Return the Boolean support of a tensor in the source carrier.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source algebra's carrier.

    Returns
    -------
    torch.Tensor
        Zero-one entries of the same shape, dtype and device.

    Raises
    ------
    TypeError
        If entries are complex.
    ValueError
        If entries lie outside the source carrier.
    """
    self._source.validate(t)
    return (~self._source.is_zero(t)).to(dtype=t.dtype)

IdentityHom

IdentityHom(q: Algebra)

Bases: AlgebraHomomorphism

The identity homomorphism id_V : V → V.

Useful as the unit of composition; f.change_base(IdentityHom(V)) leaves the morphism in V unchanged.

PARAMETER DESCRIPTION
q

The algebra mapped to itself.

TYPE: Algebra

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self, q: Algebra) -> None:
    self._q = q

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t

Embedding

Embedding(source: Algebra, target: Algebra)

Bases: AlgebraHomomorphism

The inclusion of a sub-algebra into a super-algebra.

The canonical example is Boolean ↪ ProductFuzzyAlgebra: a boolean tensor with entries in {0, 1} embeds as a product-fuzzy tensor with entries in [0, 1] whose support is the boolean's truth assignment.

Embeddings preserve every algebra operation up to the embedding inclusion; they are strict homomorphisms. The caller asserts that the source carrier lies in the target carrier and that the operations agree there; nothing checks it.

PARAMETER DESCRIPTION
source

The sub-algebra.

TYPE: Algebra

target

The algebra it is included in.

TYPE: Algebra

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self, source: Algebra, target: Algebra) -> None:
    self._source = source
    self._target = target

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t.to(dtype=torch.get_default_dtype()) if t.dtype == torch.bool else t

MarkovToProductFuzzy

MarkovToProductFuzzy()

Bases: CarrierMap

Markov → ProductFuzzyAlgebra, reading probabilities as memberships.

A Markov kernel k : A → B has rows that sum to 1 (a probability distribution over B per a∈A). Reading the per-entry probability as a fuzzy membership of (a, b) in the relation gives a ProductFuzzyAlgebra morphism.

The map clamps each entry to [0, 1]. It does not preserve the join (a sum of probabilities is not their noisy-OR), so change of base along it does not commute with composition. It is not an expectation, which integrates a function against a distribution; the DSL name expectation refers to this map.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = MARKOV
    self._target = PRODUCT_FUZZY

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t.clamp(min=0.0, max=1.0)

LogProb

LogProb()

Bases: CarrierMap

ProductFuzzyAlgebra → LogProb via log.

Maps entries in (0, 1] to (-∞, 0] for log-space computation. Entries that are exactly 0 in the source go to -inf. In practice the input is clamped to [ε, 1] first to avoid numerical blow-up.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = PRODUCT_FUZZY
    self._target = LOG_PROB

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return torch.log(t.clamp(min=1e-30))

MaxPlus

MaxPlus()

Bases: CarrierMap

ProductFuzzyAlgebra → MaxPlus via log.

The max-plus tropical algebra on the reals has tensor = addition and join = max. A ProductFuzzyAlgebra morphism transports via log so the product t-norm becomes addition in log-space; subsequent joins (which were noisy-OR in ProductFuzzyAlgebra) get replaced by max in Viterbi-style Viterbi-MAP aggregations.

LogProb and MaxPlus share the per-entry map log and differ only in the target algebra. Neither preserves the join: log of a noisy-OR is neither the logsumexp nor the maximum of the logs.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = PRODUCT_FUZZY
    self._target = MAX_PLUS

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return torch.log(t.clamp(min=1e-30))

Threshold

Threshold(tau: float = 0.5)

Bases: CarrierMap

ProductFuzzyAlgebra → Boolean via thresholding.

Entries above tau map to True; entries at or below tau map to False. It preserves order (a ≤ b ⟹ threshold(a) ≤ threshold(b)) but not the tensor: two entries just above tau threshold to True while their product may not.

PARAMETER DESCRIPTION
tau

Threshold value in [0, 1].

TYPE: float DEFAULT: 0.5

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self, tau: float = 0.5) -> None:
    if not 0.0 <= tau <= 1.0:
        raise ValueError(f"Threshold: tau must be in [0, 1]; got {tau}")
    self._tau = tau
    self._source = PRODUCT_FUZZY
    self._target = BOOLEAN

tau property

tau: float

The threshold.

RETURNS DESCRIPTION
float

Entries above it map to true.

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return (t > self._tau).to(dtype=t.dtype)

ProductFuzzyToGodel

ProductFuzzyToGodel()

Bases: CarrierMap

ProductFuzzyAlgebra → Godel, keeping each entry's value.

The map is the identity on [0, 1] (clamped), so subsequent >> composes with min and max rather than product and noisy-OR. It preserves neither operation (0.5 · 0.5 = 0.25 but min(0.5, 0.5) = 0.5), so it is a carrier map and not a homomorphism. It is not material implication, which is a binary operation (the Gödel residuum is GodelAlgebra.residuum); the DSL name material_implication refers to this map.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = PRODUCT_FUZZY
    self._target = GODEL

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t.clamp(min=0.0, max=1.0)

ProbabilityClamp

ProbabilityClamp()

Bases: CarrierMap

Real → Probability via clamping to the unit interval.

Coerces a real-valued tensor into a probability tensor by clamping entries to [0, 1]. It preserves order but not the operations: clamp(-1 + 0.5) = 0 while the bounded sum of the clamped entries is 0.5.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = REAL
    self._target = PROBABILITY

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t.clamp(min=0.0, max=1.0)

CountingFromReal

CountingFromReal()

Bases: CarrierMap

Real → Counting via floor-and-clamp-to-non-negative.

Coerces a real-valued tensor into a non-negative integer counting tensor by flooring and clamping at zero. It does not preserve the operations (floor(0.5 + 0.5) = 1 while floor(0.5) + floor(0.5) = 0); CountingToReal is a one-sided inverse on counting tensors.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = REAL
    self._target = COUNTING

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t.clamp(min=0.0).floor()

ProbabilityToReal

ProbabilityToReal()

Bases: CarrierMap

Bounded-sum product algebra → Real, the inclusion of [0, 1].

The entries already lie in [0, 1] ⊂ ℝ. The inclusion preserves the product but not the join: the source sums with a cap at 1 (0.5 ⊕ 0.75 = 1) while the real sum is 1.25.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = PROBABILITY
    self._target = REAL

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t

CountingToReal

CountingToReal()

Bases: AlgebraHomomorphism

Counting → Real (sub-algebra inclusion).

Non-negative integers embed canonically in the reals; this is the strict inclusion homomorphism. The entries keep their dtype: a natural number is already a real number.

Source code in src/quivers/core/algebra_morphisms.py
def __init__(self) -> None:
    self._source = COUNTING
    self._target = REAL

source property

source: Algebra

The source algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map reads.

target property

target: Algebra

The target algebra.

RETURNS DESCRIPTION
Algebra

The algebra whose carrier the map writes.

apply

apply(t: Tensor) -> Tensor

Apply the map to every entry.

PARAMETER DESCRIPTION
t

Entries in the source carrier.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The mapped entries, of the same shape.

Source code in src/quivers/core/algebra_morphisms.py
def apply(self, t: torch.Tensor) -> torch.Tensor:
    """Apply the map to every entry.

    Parameters
    ----------
    t : torch.Tensor
        Entries in the source carrier.

    Returns
    -------
    torch.Tensor
        The mapped entries, of the same shape.
    """
    return t

threshold

threshold(tau: float = 0.5) -> Threshold

Build a Threshold carrier map at the given threshold value.

PARAMETER DESCRIPTION
tau

The threshold; entries strictly above it map to true.

TYPE: float DEFAULT: 0.5

RETURNS DESCRIPTION
Threshold

The ProductFuzzy-to-Boolean carrier map at tau.

Source code in src/quivers/core/algebra_morphisms.py
def threshold(tau: float = 0.5) -> Threshold:
    """Build a `Threshold` carrier map at the given threshold value.

    Parameters
    ----------
    tau : float
        The threshold; entries strictly above it map to true.

    Returns
    -------
    Threshold
        The ProductFuzzy-to-Boolean carrier map at ``tau``.
    """
    return Threshold(tau)

embedding

embedding(source: Algebra, target: Algebra) -> Embedding

Build an Embedding homomorphism, a sub-algebra inclusion.

PARAMETER DESCRIPTION
source

The sub-algebra.

TYPE: Algebra

target

The super-algebra that source includes into.

TYPE: Algebra

RETURNS DESCRIPTION
Embedding

The inclusion source → target.

Source code in src/quivers/core/algebra_morphisms.py
def embedding(source: Algebra, target: Algebra) -> Embedding:
    """Build an `Embedding` homomorphism, a sub-algebra inclusion.

    Parameters
    ----------
    source : Algebra
        The sub-algebra.
    target : Algebra
        The super-algebra that ``source`` includes into.

    Returns
    -------
    Embedding
        The inclusion ``source → target``.
    """
    return Embedding(source, target)

lookup_carrier_map

lookup_carrier_map(source: Algebra, target: Algebra) -> CarrierMap | None

Look up the shipped carrier map source → target.

Identity is always available: algebras of one type yield IdentityHom(source).

PARAMETER DESCRIPTION
source

The algebra to map from.

TYPE: Algebra

target

The algebra to map to.

TYPE: Algebra

RETURNS DESCRIPTION
CarrierMap or None

The registered bridge from CARRIER_MAP_REGISTRY, or None when no canonical bridge is known.

Source code in src/quivers/core/algebra_morphisms.py
def lookup_carrier_map(source: Algebra, target: Algebra) -> CarrierMap | None:
    """Look up the shipped carrier map ``source → target``.

    Identity is always available: algebras of one type yield
    ``IdentityHom(source)``.

    Parameters
    ----------
    source : Algebra
        The algebra to map from.
    target : Algebra
        The algebra to map to.

    Returns
    -------
    CarrierMap or None
        The registered bridge from `CARRIER_MAP_REGISTRY`, or
        ``None`` when no canonical bridge is known.
    """
    if type(source) is type(target):
        return IdentityHom(source)
    return CARRIER_MAP_REGISTRY.get((source.name, target.name))

morphism_transformations

Change of base by shape-aware morphism transformations.

A quivers.core.algebra_morphisms.CarrierMap acts pointwise on tensor entries (log, threshold, max-plus lift). That handles a useful but narrow class of change-of-base moves. A transformation whose action on a morphism's tensor is shape-aware rather than strictly pointwise covers softmax-style normalizations, Bayes-inversion under a prior, L1 / L2 / spectral row normalizations, top-k truncation, and Sinkhorn balancing.

This module ships the abstract base MorphismTransformation and four concrete subclasses (Softmax, L1Normalize, L2Normalize, BayesInvert) that cover the common practical needs. Morphism.change_base accepts either a CarrierMap (pointwise) or a MorphismTransformation (shape-aware) and dispatches accordingly.

A MorphismTransformation is a map from morphisms over V to morphisms over W that acts on whole rows, columns or matrices and may carry parameter data (BayesInvert carries a prior). It promises no functoriality: normalizing a composite is in general not the composite of the normalized morphisms.

MorphismTransformation

Bases: ABC

A shape-aware change-of-base transformation.

Concrete subclasses act on a morphism's whole tensor (not entry-by-entry), optionally consuming an explicit axis specification or external parameters (e.g. a prior). The source algebra is the domain of the action; the target algebra is the resulting morphism's algebra.

The base contract is:

morphism :: V-Cat(A, B)  -->  V-Cat(A', B')

where (A', B') is determined by the transformation (often the same as (A, B) for normalizations; swapped for Bayes inversion).

source abstractmethod property

source: Algebra

The source algebra V.

target abstractmethod property

target: Algebra

The target algebra W.

apply abstractmethod

apply(tensor: Tensor, morphism) -> Tensor

Transform morphism.tensor into a tensor over the target algebra.

PARAMETER DESCRIPTION
tensor

The morphism's tensor at the current algebra.

TYPE: Tensor

morphism

The full morphism, exposed so the transformation can consult domain / codomain shape and pick the right axis.

TYPE: Morphism

Source code in src/quivers/core/morphism_transformations.py
@abstractmethod
def apply(self, tensor: torch.Tensor, morphism) -> torch.Tensor:
    """Transform ``morphism.tensor`` into a tensor over the target
    algebra.

    Parameters
    ----------
    tensor : torch.Tensor
        The morphism's tensor at the current algebra.
    morphism : Morphism
        The full morphism, exposed so the transformation can
        consult domain / codomain shape and pick the right axis.
    """

new_domain

new_domain(morphism) -> SetObject

The transformed morphism's domain. Default: unchanged.

Source code in src/quivers/core/morphism_transformations.py
def new_domain(self, morphism) -> SetObject:
    """The transformed morphism's domain. Default: unchanged."""
    return morphism.domain

new_codomain

new_codomain(morphism) -> SetObject

The transformed morphism's codomain. Default: unchanged.

Source code in src/quivers/core/morphism_transformations.py
def new_codomain(self, morphism) -> SetObject:
    """The transformed morphism's codomain. Default: unchanged."""
    return morphism.codomain

Softmax

Softmax(axis_object: SetObject, source: Algebra = PRODUCT_FUZZY)

Bases: MorphismTransformation

Softmax-normalize along an axis, producing a Markov-style kernel.

Maps a ProductFuzzyAlgebra (or Real) tensor to a row-stochastic Markov kernel by applying softmax along the axis indexed by axis_object. The output's entries lie in (0, 1) and sum to 1 along that axis.

PARAMETER DESCRIPTION
axis_object

The object whose axis the softmax is taken over.

TYPE: SetObject

source

The morphism's algebra before softmax. Default PRODUCT_FUZZY.

TYPE: Algebra DEFAULT: PRODUCT_FUZZY

Source code in src/quivers/core/morphism_transformations.py
def __init__(
    self,
    axis_object: SetObject,
    source: Algebra = PRODUCT_FUZZY,
) -> None:

    self._axis_object = axis_object
    self._source = source
    self._target = MARKOV

L1Normalize

L1Normalize(axis_object: SetObject, source: Algebra = REAL)

Bases: MorphismTransformation

L1-normalize along an axis: divide each entry by the row sum.

Maps a non-negative real tensor to one whose entries sum to 1 along the given axis. The output is row-stochastic on that axis; semantically identical to a Markov kernel.

PARAMETER DESCRIPTION
axis_object

The object whose axis is normalized.

TYPE: SetObject

source

Default REAL.

TYPE: Algebra DEFAULT: REAL

Source code in src/quivers/core/morphism_transformations.py
def __init__(
    self,
    axis_object: SetObject,
    source: Algebra = REAL,
) -> None:

    self._axis_object = axis_object
    self._source = source
    self._target = MARKOV

L2Normalize

L2Normalize(axis_object: SetObject, source: Algebra = REAL)

Bases: MorphismTransformation

L2-normalize along an axis: divide each entry by the row norm.

Maps a real-valued tensor to one whose entries lie on the unit L2 sphere along the given axis. The result is still in the source algebra (Real), with rows rescaled to unit length.

PARAMETER DESCRIPTION
axis_object

The object whose axis is normalized.

TYPE: SetObject

source

Default REAL. The target equals the source.

TYPE: Algebra DEFAULT: REAL

Source code in src/quivers/core/morphism_transformations.py
def __init__(
    self,
    axis_object: SetObject,
    source: Algebra = REAL,
) -> None:
    self._axis_object = axis_object
    self._source = source
    self._target = source

BayesInvert

BayesInvert(prior: Tensor)

Bases: MorphismTransformation

Bayes-invert a Markov kernel under a prior.

Given a Markov kernel f : A -> B and a prior pi : 1 -> A, the Bayes-inverse f^{-1}_pi : B -> A is the kernel satisfying

f^{-1}_pi(a | b) = f(b | a) * pi(a) / sum_a' f(b | a') * pi(a')

Mathematically this is the disintegration of the joint distribution along the second margin. The domain and codomain swap roles in the result.

PARAMETER DESCRIPTION
prior

Prior probabilities over the source's first object. Shape (|A|,); must sum to 1.

TYPE: Tensor

Source code in src/quivers/core/morphism_transformations.py
def __init__(self, prior: torch.Tensor) -> None:

    if prior.dim() != 1:
        raise ValueError(f"BayesInvert: prior must be 1-D; got {prior.dim()}-D")
    if not torch.isclose(prior.sum(), torch.ones(())):
        raise ValueError(
            f"BayesInvert: prior must sum to 1; got sum={float(prior.sum()):.4f}"
        )
    if (prior < 0).any():
        raise ValueError("BayesInvert: prior entries must be non-negative")
    self._prior = prior.clone()
    self._source = MARKOV
    self._target = MARKOV

softmax

softmax(axis_object: SetObject) -> Softmax

Build a Softmax transformation along axis_object.

PARAMETER DESCRIPTION
axis_object

The object whose axis the softmax is taken over.

TYPE: SetObject

RETURNS DESCRIPTION
Softmax

The ProductFuzzy-to-Markov transformation.

Source code in src/quivers/core/morphism_transformations.py
def softmax(axis_object: SetObject) -> Softmax:
    """Build a `Softmax` transformation along ``axis_object``.

    Parameters
    ----------
    axis_object : SetObject
        The object whose axis the softmax is taken over.

    Returns
    -------
    Softmax
        The ProductFuzzy-to-Markov transformation.
    """
    return Softmax(axis_object)

l1_normalize

l1_normalize(axis_object: SetObject) -> L1Normalize

Build an L1Normalize transformation along axis_object.

PARAMETER DESCRIPTION
axis_object

The object whose axis is normalized.

TYPE: SetObject

RETURNS DESCRIPTION
L1Normalize

The Real-to-Markov transformation.

Source code in src/quivers/core/morphism_transformations.py
def l1_normalize(axis_object: SetObject) -> L1Normalize:
    """Build an `L1Normalize` transformation along ``axis_object``.

    Parameters
    ----------
    axis_object : SetObject
        The object whose axis is normalized.

    Returns
    -------
    L1Normalize
        The Real-to-Markov transformation.
    """
    return L1Normalize(axis_object)

l2_normalize

l2_normalize(axis_object: SetObject) -> L2Normalize

Build an L2Normalize transformation along axis_object.

PARAMETER DESCRIPTION
axis_object

The object whose axis is normalized.

TYPE: SetObject

RETURNS DESCRIPTION
L2Normalize

The Real-to-Real transformation.

Source code in src/quivers/core/morphism_transformations.py
def l2_normalize(axis_object: SetObject) -> L2Normalize:
    """Build an `L2Normalize` transformation along ``axis_object``.

    Parameters
    ----------
    axis_object : SetObject
        The object whose axis is normalized.

    Returns
    -------
    L2Normalize
        The Real-to-Real transformation.
    """
    return L2Normalize(axis_object)

bayes_invert

bayes_invert(prior) -> BayesInvert

Build a BayesInvert transformation from a prior.

prior may be a 1-D torch.Tensor (used directly) or any object that exposes a .tensor attribute (the morphism convention used throughout the V-Cat layer). Duck typing on .tensor avoids a circular import between quivers.core.morphisms and this module. The morphism form is what the DSL feeds in when the user writes change_base(bayes_invert(prior_morph)).

PARAMETER DESCRIPTION
prior

The prior over the kernel's domain, as a tensor or as a morphism whose tensor holds it. A prior that does not sum to 1 is clamped to be non-negative and renormalized.

TYPE: Tensor or Morphism

RETURNS DESCRIPTION
BayesInvert

The Bayes-inversion transformation under prior.

RAISES DESCRIPTION
TypeError

If prior is neither a tensor nor carries a tensor.

ValueError

If prior sums to zero.

Source code in src/quivers/core/morphism_transformations.py
def bayes_invert(prior) -> BayesInvert:
    """Build a `BayesInvert` transformation from a prior.

    ``prior`` may be a 1-D `torch.Tensor` (used directly)
    or any object that exposes a ``.tensor`` attribute (the
    morphism convention used throughout the V-Cat layer). Duck
    typing on ``.tensor`` avoids a circular import between
    [`quivers.core.morphisms`][quivers.core.morphisms] and this module. The morphism
    form is what the DSL feeds in when the user writes
    ``change_base(bayes_invert(prior_morph))``.

    Parameters
    ----------
    prior : torch.Tensor or Morphism
        The prior over the kernel's domain, as a tensor or as a
        morphism whose ``tensor`` holds it. A prior that does not sum
        to 1 is clamped to be non-negative and renormalized.

    Returns
    -------
    BayesInvert
        The Bayes-inversion transformation under ``prior``.

    Raises
    ------
    TypeError
        If ``prior`` is neither a tensor nor carries a ``tensor``.
    ValueError
        If ``prior`` sums to zero.
    """
    if isinstance(prior, torch.Tensor):
        tensor = prior
    elif hasattr(prior, "tensor"):
        tensor = prior.tensor.detach().clone()
    else:
        raise TypeError(
            f"bayes_invert: expected Tensor or .tensor-bearing "
            f"morphism prior; got {type(prior).__name__}"
        )
    flat = tensor.flatten()
    total = flat.sum()
    if total.abs() < 1e-12:
        raise ValueError("bayes_invert: prior sums to zero; cannot normalize")
    if not torch.isclose(total, torch.tensor(1.0), atol=1e-5):
        flat = flat.clamp(min=0.0)
        flat = flat / flat.sum().clamp(min=1e-12)
    return BayesInvert(flat)

trans

First-class transformation composition.

A transformation in quivers is either a quivers.core.algebra_morphisms.CarrierMap (pointwise, lax monoidal) or a quivers.core.morphism_transformations.MorphismTransformation (shape-aware). Both expose a source and target algebra and an apply that consumes a morphism's tensor.

This module gives them a composition operation: compose_trans(t1, t2, ...) returns a TransSeq value that applies the steps in order when handed to Morphism.change_base. Adjacent target and source are type-checked at compose time. Nested TransSeq are flattened so the resulting steps tuple is always a single flat sequence of base transformations.

This is the Python-side surface for the DSL's t1 >>> t2 operator: in the .qvr surface, let pipe = softmax(B) >>> expectation builds the same value that compose_trans(softmax(B), MARKOV_TO_PRODUCT_FUZZY) builds here.

TransSeq

TransSeq(steps: tuple[TransValue, ...])

Sequence of transformations applied left-to-right.

Constructed by compose_trans; consumed by Morphism.change_base. Each adjacent target / source boundary in steps is verified at construction time, so apply does not have to revalidate.

A TransSeq itself exposes the same source / target / name interface as a single transformation, so it can be fed into further compose_trans calls and the nesting is flattened.

Source code in src/quivers/core/trans.py
def __init__(self, steps: tuple[TransValue, ...]) -> None:
    if len(steps) < 2:
        raise ValueError(
            "TransSeq: requires at least two steps; a "
            "single-step trans value is the base "
            "transformation itself, not a sequence"
        )
    for i in range(len(steps) - 1):
        tgt = steps[i].target
        src = steps[i + 1].source
        if type(tgt) is not type(src):
            raise TypeError(
                f"compose_trans: target of step {i} "
                f"({tgt.name!r}) does not match source of "
                f"step {i + 1} ({src.name!r})"
            )
    self._steps: tuple[TransValue, ...] = steps
    self._source = steps[0].source
    self._target = steps[-1].target

compose_trans

compose_trans(*steps: TransValue | TransSeq) -> TransSeq

Compose two or more transformations into a single sequence.

Each argument is either a base transformation (a CarrierMap or MorphismTransformation) or another TransSeq whose steps are inlined. The resulting sequence is flat; nested compositions never appear in TransSeq.steps.

PARAMETER DESCRIPTION
*steps

Two or more transformations.

TYPE: TransValue or TransSeq DEFAULT: ()

RETURNS DESCRIPTION
TransSeq

The composed sequence with source = steps[0].source and target = steps[-1].target.

RAISES DESCRIPTION
ValueError

If fewer than two steps are supplied.

TypeError

If two adjacent steps' target / source algebras differ.

Source code in src/quivers/core/trans.py
def compose_trans(*steps: TransValue | TransSeq) -> TransSeq:
    """Compose two or more transformations into a single sequence.

    Each argument is either a base transformation (a
    ``CarrierMap`` or ``MorphismTransformation``) or
    another `TransSeq` whose steps are inlined.  The
    resulting sequence is flat; nested compositions never appear
    in `TransSeq.steps`.

    Parameters
    ----------
    *steps : TransValue or TransSeq
        Two or more transformations.

    Returns
    -------
    TransSeq
        The composed sequence with ``source = steps[0].source``
        and ``target = steps[-1].target``.

    Raises
    ------
    ValueError
        If fewer than two steps are supplied.
    TypeError
        If two adjacent steps' target / source algebras differ.
    """
    if len(steps) < 2:
        raise ValueError("compose_trans: requires at least two transformations")
    flat: list[TransValue] = []
    for step in steps:
        if isinstance(step, TransSeq):
            flat.extend(step.steps)
        else:
            flat.append(step)
    return TransSeq(tuple(flat))

The carrier map singletons, their registry, and the TransValue alias are documented on the core overview.

Cited sources

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.