Skip to content

Objects

Categorical objects including finite and enumerated sets, products, coproducts, free monoids, and free residuated universes.

objects

Categorical objects: finite sets, products, coproducts, and free monoids.

The set-object family is a sum type with four variants — FinSet, ProductSet, CoproductSet, FreeMonoid — discriminated by kind. SetObject is the dx.TaggedUnion root that gathers them; X * Y and X + Y work on any pair of variants.

SetObject didactic-model

SetObject()

Bases: TaggedUnion

The category of finite sets, product sets, and coproduct sets.

Variants share two derived properties (size, shape) and the * / + operators for product and coproduct construction.

size property

size: int

Total cardinality of the set.

shape property

shape: tuple[int, ...]

Tensor dimension shape.

ndim property

ndim: int

Number of tensor dimensions.

FinSet didactic-model

FinSet(*, name: str, cardinality: int = field(converter=_check_cardinality), kind: Literal['finset'] = 'finset')

Bases: SetObject

A named finite set with a fixed cardinality.

ATTRIBUTE DESCRIPTION
name

Human-readable name for the set.

TYPE: str

cardinality

Number of elements (must be >= 1).

TYPE: int

ProductSet didactic-model

ProductSet(*, components: tuple[SetObject, ...] = field(default=(), converter=_flatten_products), kind: Literal['product_set'] = 'product_set')

Bases: SetObject

Cartesian product of finite sets.

Nested products are flattened: ProductSet(components=(A, ProductSet(components=(B, C)))) constructs to ProductSet with components == (A, B, C).

CoproductSet didactic-model

CoproductSet(*, components: tuple[SetObject, ...] = field(default=(), converter=_flatten_coproducts), kind: Literal['coproduct_set'] = 'coproduct_set')

Bases: SetObject

Tagged union (coproduct) of finite sets.

The flat cardinality is the sum of component cardinalities; the shape is a single dimension of that total size with offsets recoverable from offsets.

offsets

offsets() -> tuple[int, ...]

Per-component flat offsets, computed from cumulative sizes.

Source code in src/quivers/core/objects.py
@dx.derived
def offsets(self) -> tuple[int, ...]:
    """Per-component flat offsets, computed from cumulative sizes."""
    out: list[int] = []
    running = 0
    for c in self.components:
        out.append(running)
        running += c.size
    return tuple(out)

offset

offset(index: int) -> int

Return the flat offset for the i-th component.

Source code in src/quivers/core/objects.py
def offset(self, index: int) -> int:
    """Return the flat offset for the i-th component."""
    return self.offsets[index]

component_range

component_range(index: int) -> tuple[int, int]

Return (start, end) flat indices for the i-th component.

Source code in src/quivers/core/objects.py
def component_range(self, index: int) -> tuple[int, int]:
    """Return ``(start, end)`` flat indices for the i-th component."""
    start = self.offsets[index]
    end = start + self.components[index].size
    return (start, end)

FreeMonoid didactic-model

FreeMonoid(*, generators: FinSet, max_length: int, kind: Literal['free_monoid'] = 'free_monoid')

Bases: SetObject

Free monoid on a generator set, truncated to max_length.

Represents all tuples (strings) from elements of generators with length 0 through max_length. Internally a coproduct Unit + G + G×G + ... + G^max_length; obtain it via as_coproduct.

ATTRIBUTE DESCRIPTION
generators

The generator set.

TYPE: FinSet

max_length

Maximum string length (inclusive).

TYPE: int

as_coproduct

as_coproduct() -> CoproductSet

Return the underlying coproduct view.

Source code in src/quivers/core/objects.py
def as_coproduct(self) -> CoproductSet:
    """Return the underlying coproduct view."""
    return self._coproduct

encode

encode(word: tuple[int, ...]) -> int

Encode a word (tuple of generator indices) to a flat index.

Source code in src/quivers/core/objects.py
def encode(self, word: tuple[int, ...]) -> int:
    """Encode a word (tuple of generator indices) to a flat index."""
    k = len(word)
    if k > self.max_length:
        raise ValueError(f"word length {k} exceeds max_length {self.max_length}")
    g = self.generators.cardinality
    base = self.offset(k)
    if k == 0:
        return base
    idx = 0
    for w in word:
        if not 0 <= w < g:
            raise ValueError(f"generator index {w} out of range [0, {g})")
        idx = idx * g + w
    return base + idx

decode

decode(flat_index: int) -> tuple[int, ...]

Decode a flat index back to a word.

Source code in src/quivers/core/objects.py
def decode(self, flat_index: int) -> tuple[int, ...]:
    """Decode a flat index back to a word."""
    if not 0 <= flat_index < self.size:
        raise ValueError(f"flat_index {flat_index} out of range [0, {self.size})")
    g = self.generators.cardinality
    cop = self._coproduct
    for k in range(len(cop.components)):
        start, end = cop.component_range(k)
        if start <= flat_index < end:
            local = flat_index - start
            if k == 0:
                return ()
            digits: list[int] = []
            for _ in range(k):
                digits.append(local % g)
                local //= g
            digits.reverse()
            return tuple(digits)
    raise RuntimeError("unreachable")

EnumSet didactic-model

EnumSet(*, name: str, elements: tuple[str, ...], kind: Literal['enum_set'] = 'enum_set')

Bases: SetObject

A finite set whose elements have explicit names.

Unlike FinSet, whose elements are anonymous integers 0..cardinality-1, an EnumSet carries a tuple of element names; the cardinality is len(elements). Names must be unique.

Used for declaring atom collections (e.g. categorial-grammar atoms like {NP, S, VP}) that other constructions reference by name.

ATTRIBUTE DESCRIPTION
name

Human-readable name for the set.

TYPE: str

elements

The element names. Must be unique and non-empty.

TYPE: tuple of str

index

index(name: str) -> int

Return the integer index of the element name.

Source code in src/quivers/core/objects.py
def index(self, name: str) -> int:
    """Return the integer index of the element ``name``."""
    try:
        return self.elements.index(name)
    except ValueError as e:
        raise KeyError(
            f"{name!r} is not an element of EnumSet {self.name!r}"
        ) from e

FreeResiduated didactic-model

FreeResiduated(*, generators: EnumSet, depth: int = 1, ops: tuple[str, ...] = ('slash',), kind: Literal['free_residuated'] = 'free_residuated')

Bases: SetObject

The residuated category universe over a generator set.

Closes the generator atoms under the residuated monoidal connectives (/, \, *, optional ◇ / □) up to a bounded nesting depth. The runtime carrier is a finite enumeration of all admissible category strings produced by quivers.stochastic.categories.CategorySystem.from_generators.

ATTRIBUTE DESCRIPTION
generators

The atom generators (e.g. EnumSet(name='Atoms', elements=('NP', 'S', 'VP'))).

TYPE: EnumSet

depth

Maximum nesting depth of category constructors. depth=0 gives only atoms; each increment doubles (slash) or grows polynomially (product).

TYPE: int

ops

The connectives to close under. Allowed names: "slash" (both / and \), "product" (*), "unit" (the monoidal unit), "diamond" (◇), "box" (□).

TYPE: tuple of str

system

system() -> object

Return the underlying CategorySystem.

The system is constructed on each call (cheap for small depths; callers expecting to use it multiple times should hold a reference). Storing the result inside the model would require a non-frozen field, which is incompatible with the dx.Model contract.

Source code in src/quivers/core/objects.py
def system(self) -> object:
    """Return the underlying `CategorySystem`.

    The system is constructed on each call (cheap for small depths;
    callers expecting to use it multiple times should hold a
    reference). Storing the result inside the model would require
    a non-frozen field, which is incompatible with the dx.Model
    contract.
    """
    from quivers.stochastic.categories import CategorySystem

    return CategorySystem.from_generators(
        list(self.generators.elements),
        constructors=list(self.ops),
        max_depth=self.depth,
    )

Package constants

The constants and type aliases of quivers.core: the terminal object, the numerical margin, the algebra and homomorphism singletons, the homomorphism registry, and the transformation alias.

Core types and functions of the quivers package.

The package re-exports every public name of its modules:

  • objects: finite sets and their products, coproducts, and free monoids;
  • algebras: the enrichment algebras, their composition rules, and singletons;
  • algebra_morphisms: homomorphisms between algebras, for change of base;
  • morphism_transformations: shape-aware transformations such as softmax;
  • trans: sequences of transformations built by compose_trans;
  • morphisms: the Morphism hierarchy and its factory functions;
  • wiring: einsum wiring rules for contractions;
  • tensor_ops: noisy-OR contraction and componentwise lifting.

Unit module-attribute

Unit: FinSet = FinSet(name='1', cardinality=1)

The terminal object, the one-element finite set.

EPS module-attribute

EPS: float = 1e-07

The default margin by which clamp_probs keeps probabilities away from 0 and 1.

PRODUCT_FUZZY module-attribute

PRODUCT_FUZZY = ProductFuzzyAlgebra()

The ProductFuzzyAlgebra singleton, the default algebra of every morphism.

BOOLEAN module-attribute

BOOLEAN = BooleanAlgebra()

The BooleanAlgebra singleton, enriching crisp binary relations.

LUKASIEWICZ module-attribute

LUKASIEWICZ = LukasiewiczAlgebra()

The LukasiewiczAlgebra singleton.

GODEL module-attribute

GODEL = GodelAlgebra()

The GodelAlgebra singleton.

TROPICAL module-attribute

TROPICAL = TropicalAlgebra()

The TropicalAlgebra singleton, the min-plus enrichment of Lawvere metric spaces.

MAX_PLUS module-attribute

MAX_PLUS = MaxPlusAlgebra()

The MaxPlusAlgebra singleton, the Viterbi semiring.

LOG_PROB module-attribute

LOG_PROB = LogProbAlgebra()

The LogProbAlgebra singleton, the log-space sum-product semiring.

REAL module-attribute

REAL = RealAlgebra()

The RealAlgebra singleton.

PROBABILITY module-attribute

PROBABILITY = ProbabilityAlgebra()

The ProbabilityAlgebra singleton.

COUNTING module-attribute

COUNTING = CountingAlgebra()

The CountingAlgebra singleton.

MARKOV module-attribute

MARKOV = MarkovAlgebra()

The MarkovAlgebra singleton, composing stochastic matrices.

REICHENBACH module-attribute

REICHENBACH = PRODUCT_FUZZY.dual()

The de Morgan dual of PRODUCT_FUZZY, the canonical probabilistic-implication composition.

BOOLEAN_DUAL module-attribute

BOOLEAN_DUAL = BOOLEAN.dual()

The de Morgan dual of BOOLEAN, which swaps its tensor and join.

DUAL_LUKASIEWICZ module-attribute

DUAL_LUKASIEWICZ = LUKASIEWICZ.dual()

The de Morgan dual of LUKASIEWICZ, which swaps its tensor and join.

DUAL_GODEL module-attribute

DUAL_GODEL = GODEL.dual()

The de Morgan dual of GODEL, which swaps its tensor and join.

EXPECTATION module-attribute

EXPECTATION = Expectation()

The Expectation homomorphism singleton, Markov to ProductFuzzy.

LOG_PROB_HOM module-attribute

LOG_PROB_HOM = LogProb()

The LogProb homomorphism singleton, ProductFuzzy to LogProb.

MAX_PLUS_HOM module-attribute

MAX_PLUS_HOM = MaxPlus()

The MaxPlus homomorphism singleton, ProductFuzzy to MaxPlus.

MATERIAL_IMPLICATION module-attribute

MATERIAL_IMPLICATION = MaterialImplication()

The MaterialImplication homomorphism singleton, ProductFuzzy to Godel.

PROBABILITY_CLAMP module-attribute

PROBABILITY_CLAMP = ProbabilityClamp()

The ProbabilityClamp homomorphism singleton, Real to Probability.

COUNTING_FROM_REAL module-attribute

COUNTING_FROM_REAL = CountingFromReal()

The CountingFromReal homomorphism singleton, Real to Counting.

PROBABILITY_TO_REAL module-attribute

PROBABILITY_TO_REAL = ProbabilityToReal()

The ProbabilityToReal homomorphism singleton, Probability to Real.

COUNTING_TO_REAL module-attribute

COUNTING_TO_REAL = CountingToReal()

The CountingToReal homomorphism singleton, Counting to Real.

HOMOMORPHISM_REGISTRY module-attribute

HOMOMORPHISM_REGISTRY: dict[tuple[str, str], AlgebraHomomorphism] = {('Markov', 'ProductFuzzy'): EXPECTATION, ('ProductFuzzy', 'LogProb'): LOG_PROB_HOM, ('ProductFuzzy', 'MaxPlus'): MAX_PLUS_HOM, ('ProductFuzzy', 'Boolean'): Threshold(0.5), ('ProductFuzzy', 'Godel'): MATERIAL_IMPLICATION, ('Boolean', 'ProductFuzzy'): Embedding(BOOLEAN, PRODUCT_FUZZY), ('Real', 'Probability'): PROBABILITY_CLAMP, ('Real', 'Counting'): COUNTING_FROM_REAL, ('Probability', 'Real'): PROBABILITY_TO_REAL, ('Counting', 'Real'): COUNTING_TO_REAL}

The canonical homomorphisms keyed by (source.name, target.name), so compiler and user code can look up the standard bridge between two algebras rather than construct one by hand.

TransValue

A single base transformation: either a AlgebraHomomorphism (pointwise) or a MorphismTransformation (shape-aware).