Skip to content

Objects

An object names what a tensor axis ranges over, so a set of three users and a set of three items have the same size and different meanings. The module defines finite and enumerated sets, products and coproducts (tuples and tagged alternatives) (Mac Lane, 1998), free monoids, and FreeResiduated, the categorial (Lambek) types built from a set of atoms with /, \, and * up to a fixed depth (Lambek, 1958). Finite objects index tensor axes. A StringSet ranges over all finite strings on its alphabet. Its bounded method returns a FreeMonoid after checking the cardinality of the length restriction. Continuous supports have their own space types.

objects

Objects for typed morphisms, including finite sets and string sets.

SetObject is the tagged union of the available object representations. X * Y and X + Y construct products and coproducts without assigning tensor axes to unbounded objects.

SetObject didactic-model

SetObject()

Bases: TaggedUnion

Set object with products and coproducts.

Finite representations provide a cardinality and tensor shape.

size property

size: int

Total cardinality when the object admits a finite tensor.

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
    length = (
        bisect_right(
            range(self.max_length + 1), flat_index, key=self._length_offset
        )
        - 1
    )
    local = flat_index - self._length_offset(length)
    digits: list[int] = []
    for _ in range(length):
        local, digit = divmod(local, g)
        digits.append(digit)
    return tuple(reversed(digits))

StringSet didactic-model

StringSet(*, alphabet: FinSet, kind: Literal['string_set'] = 'string_set')

Bases: SetObject

All finite strings over a finite alphabet, including the empty string.

ATTRIBUTE DESCRIPTION
alphabet

Alphabet with symbols identified by indices in 0..alphabet.cardinality-1.

TYPE: FinSet

bounded

bounded(max_length: int, *, max_size: int) -> FreeMonoid

Restrict to words of length at most a specified bound.

PARAMETER DESCRIPTION
max_length

Maximum length of the accepted words, inclusive.

TYPE: int

max_size

Maximum permitted finite cardinality, including the empty word.

TYPE: int

RETURNS DESCRIPTION
FreeMonoid

The length-bounded carrier in length-then-lexicographic order.

RAISES DESCRIPTION
ValueError

If a bound is invalid or the restriction exceeds the size limit.

Source code in src/quivers/core/objects.py
def bounded(self, max_length: int, *, max_size: int) -> FreeMonoid:
    """Restrict to words of length at most a specified bound.

    Parameters
    ----------
    max_length : int
        Maximum length of the accepted words, inclusive.
    max_size : int
        Maximum permitted finite cardinality, including the empty word.

    Returns
    -------
    FreeMonoid
        The length-bounded carrier in length-then-lexicographic order.

    Raises
    ------
    ValueError
        If a bound is invalid or the restriction exceeds the size limit.
    """
    if type(max_length) is not int or max_length < 0:
        raise ValueError("max_length must be a nonnegative integer")
    if type(max_size) is not int or max_size < 1:
        raise ValueError("max_size must be a positive integer")
    alphabet_size = self.alphabet.cardinality
    if alphabet_size == 1:
        if max_length >= max_size:
            raise ValueError("bounded StringSet exceeds max_size")
    else:
        # Stop as soon as the geometric sum exceeds the budget.
        # This avoids a huge exponent when max_length itself is huge.
        size = words_at_length = 1
        for _ in range(max_length):
            words_at_length *= alphabet_size
            size += words_at_length
            if size > max_size:
                raise ValueError("bounded StringSet exceeds max_size")
    return FreeMonoid(generators=self.alphabet, max_length=max_length)

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 finite set of Lambek-calculus types over a generator set.

The elements are the formulas built from the generator atoms with the residuated connectives (/, \, *, optional ◇ / □) up to a bounded nesting depth, the types of the Lambek calculus [Lambek (1958)]. The set is a finite set of formulas, not a category, and it is not closed under the connectives. 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 adds the formulas whose outermost connective joins two formulas of smaller depth.

TYPE: int

ops

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

TYPE: tuple of str

References

Lambek, J. (1958). The mathematics of sentence structure. The American Mathematical Monthly, 65(3), 154-170. doi:10.1080/00029890.1958.11989160

system

system() -> CategorySystem

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.

RETURNS DESCRIPTION
CategorySystem

The category inventory generated by the declared constructors.

Source code in src/quivers/core/objects.py
def system(self) -> CategorySystem:
    """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.

    Returns
    -------
    CategorySystem
        The category inventory generated by the declared constructors.
    """
    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;
  • laws: laws, the evidence for them, and the structures that claim them;
  • 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;
  • elimination: plans of contractions by variable elimination;
  • wiring: einsum wiring rules for contractions;
  • tensor_ops: noisy-OR contraction and componentwise lifting;
  • exact: tensors of exact rationals, and the operations they admit;
  • rationals: the field of rationals as an exact algebra.

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 = StandardMVAlgebra()

The StandardMVAlgebra 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 = BoundedSumProductAlgebra()

The BoundedSumProductAlgebra 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.

MARKOV_TO_PRODUCT_FUZZY module-attribute

MARKOV_TO_PRODUCT_FUZZY = MarkovToProductFuzzy()

The MarkovToProductFuzzy carrier-map singleton, Markov to ProductFuzzy.

LOG_PROB_MAP module-attribute

LOG_PROB_MAP = LogProb()

The LogProb carrier-map singleton, ProductFuzzy to LogProb.

MAX_PLUS_MAP module-attribute

MAX_PLUS_MAP = MaxPlus()

The MaxPlus carrier-map singleton, ProductFuzzy to MaxPlus.

PRODUCT_FUZZY_TO_GODEL module-attribute

PRODUCT_FUZZY_TO_GODEL = ProductFuzzyToGodel()

The ProductFuzzyToGodel carrier-map singleton, ProductFuzzy to Godel.

PROBABILITY_CLAMP module-attribute

PROBABILITY_CLAMP = ProbabilityClamp()

The ProbabilityClamp carrier-map singleton, Real to Probability.

COUNTING_FROM_REAL module-attribute

COUNTING_FROM_REAL = CountingFromReal()

The CountingFromReal carrier-map singleton, Real to Counting.

PROBABILITY_TO_REAL module-attribute

PROBABILITY_TO_REAL = ProbabilityToReal()

The ProbabilityToReal carrier-map singleton, Probability to Real.

COUNTING_TO_REAL module-attribute

COUNTING_TO_REAL = CountingToReal()

The CountingToReal homomorphism singleton, Counting to Real.

CARRIER_MAP_REGISTRY module-attribute

CARRIER_MAP_REGISTRY: dict[tuple[str, str], CarrierMap] = {('Markov', 'ProductFuzzy'): MARKOV_TO_PRODUCT_FUZZY, ('ProductFuzzy', 'LogProb'): LOG_PROB_MAP, ('ProductFuzzy', 'MaxPlus'): MAX_PLUS_MAP, ('ProductFuzzy', 'Boolean'): Threshold(0.5), ('ProductFuzzy', 'Godel'): PRODUCT_FUZZY_TO_GODEL, ('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 shipped carrier maps 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 CarrierMap (pointwise) or a MorphismTransformation (shape-aware).

Cited sources

Saunders Mac Lane. Categories for the Working Mathematician. Volume 5 of Graduate Texts in Mathematics. Springer, 2 edition, 1998. URL: https://link.springer.com/book/10.1007/978-1-4757-4721-8, doi:10.1007/978-1-4757-4721-8.

Joachim Lambek. The Mathematics of Sentence Structure. The American Mathematical Monthly, 65(3):154–170, 1958. URL: https://www.tandfonline.com/doi/abs/10.1080/00029890.1958.11989160, doi:10.1080/00029890.1958.11989160.