Objects

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

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

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

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

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

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
146
147
148
149
150
151
152
153
154
@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
164
165
166
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
168
169
170
171
172
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

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
219
220
221
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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

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
324
325
326
327
328
329
330
331
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

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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
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,
    )