Skip to content

Semirings

Semiring instances, the semiring a deduction runs in, the check that a cyclic deduction has a fixpoint, and the free instance of a deduction with its specializations. check_instance checks an instance against its theory, free_chart computes a deduction's chart in the free commutative semiring, and specialize evaluates it along a homomorphism. The semirings reference describes the surface, and the semantics states the constructions and guarantees.

semirings

Semirings as theory parameters of deductions.

std.semiring declares the semiring theories (Semiring, ClosedSemiring, OmegaContinuousSemiring) and the shipped instances. A semiring declaration names an instance realized by an algebra of quivers.core.algebras, checked against its theory's laws (check_instance); a deduction header names the instance it runs in, or the theory it is generic over (deduction_semiring); a deduction whose rules may derive an item from itself needs a semiring whose theory guarantees the fixpoint (require_convergence). The free instance of a deduction is its derivation forest, computed once and specialized to any instance along the unique homomorphism (free_chart, specialize).

STOP_OPTION module-attribute

STOP_OPTION = 'tolerance'

The option that declares how a deduction's iteration stops.

MAX_MONOMIALS module-attribute

MAX_MONOMIALS = 100000

The most monomials a polynomial is expanded to.

ALGEBRAS module-attribute

ALGEBRAS: Mapping[str, Semiring] = MappingProxyType({member.name: member for member in KERNEL_ALGEBRAS.values()})

The shipped algebras an instance may be realized by, by their names.

CARRIERS module-attribute

CARRIERS: Mapping[str, TypeExpr] = MappingProxyType({render_static(carrier): carrier for carrier in KERNEL_CARRIERS})

The kernel types an instance's elements may live in, by their names.

CUT_OPTION module-attribute

CUT_OPTION = 'semiring'

The option key a deduction's semiring is no longer given by.

LOG_SEMIRING module-attribute

The semiring a deduction without a semiring parameter runs in.

CATALOGUE module-attribute

CATALOGUE: Mapping[tuple[str, str], Law] = {(SEMIRING_THEORY, 'plus_assoc'): PLUS_ASSOCIATIVE, (SEMIRING_THEORY, 'plus_comm'): PLUS_COMMUTATIVE, (SEMIRING_THEORY, 'plus_unit'): PLUS_UNIT, (SEMIRING_THEORY, 'times_assoc'): TIMES_ASSOCIATIVE, (SEMIRING_THEORY, 'times_comm'): TIMES_COMMUTATIVE, (SEMIRING_THEORY, 'times_unit'): TIMES_UNIT, (SEMIRING_THEORY, 'distrib'): DISTRIBUTIVE, (SEMIRING_THEORY, 'annihilate'): ZERO_ANNIHILATES, (CLOSED_THEORY, 'star_unfold'): STAR_LEAST_SOLUTION}

Each law of std.semiring by its origin and name, and its counterpart in the law catalogue whose claim by an algebra establishes it.

CLOSED_THEORY module-attribute

CLOSED_THEORY = flat_name(STANDARD_MODULE, 'ClosedSemiring')

The theory whose instances have a closure.

CONVERGENT_THEORIES module-attribute

CONVERGENT_THEORIES: frozenset[str] = frozenset({CLOSED_THEORY, OMEGA_CONTINUOUS_THEORY})

The theories whose instances guarantee the fixpoint of a cyclic deduction.

MAX_ASSIGNMENTS module-attribute

MAX_ASSIGNMENTS = 4096

The most assignments a law is evaluated at.

OMEGA_CONTINUOUS_THEORY module-attribute

OMEGA_CONTINUOUS_THEORY = flat_name(STANDARD_MODULE, 'OmegaContinuousSemiring')

The theory whose instances are ω-continuous.

SEMIRING_THEORY module-attribute

SEMIRING_THEORY = flat_name(STANDARD_MODULE, 'Semiring')

The theory every semiring instance's theory includes.

SPREAD module-attribute

SPREAD: tuple[float, ...] = (-math.inf, -2.0, -0.5, 0.0, 0.25, 0.5, 1.0, 2.0, 3.0, math.inf)

The elements, besides the units, a law is evaluated at on an infinite carrier, each kept only when the algebra and the carrier hold it.

STANDARD_MODULE module-attribute

STANDARD_MODULE = SourceModule(path=('std', 'semiring'))

The module that declares the semiring theories.

Monomial

Monomial = tuple[tuple[tuple[str, int, Bindings], int], ...]

A product of generators, each with its exponent, sorted.

Polynomial

Polynomial = dict[Monomial, int]

An element of the free commutative semiring: monomials and coefficients.

RulePattern didactic-model

RulePattern(*, name: str, premises: tuple[Pattern, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), conclusion: Pattern = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A rule's premises and conclusion as patterns over the deduction's items.

PARAMETER DESCRIPTION
name

The rule's name.

TYPE: str

premises

Its premises.

TYPE: tuple of Pattern DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

conclusion

Its conclusion.

TYPE: Pattern DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

AlgebraHomomorphism

AlgebraHomomorphism(semiring: ChartSemiring, system: DeductionSystem | None = None, *, convergent: bool = False, name: str = '')

Bases: Homomorphism[Tensor]

The homomorphism into a chart semiring a deduction's run defines.

A rule instance goes to the rule's own weight in the semiring, which is what the deduction's compiled rule multiplies into every conclusion; an input occurrence goes to its weight, which is a log weight in a semiring whose elements are log weights and the unit in any other, as the deduction's lexicon reads it. Specializing a free chart along it therefore equals running the deduction in the semiring.

PARAMETER DESCRIPTION
semiring

The target.

TYPE: ChartSemiring

system

The deduction whose weights the generators go to; the chart's own deduction when None.

TYPE: DeductionSystem or None DEFAULT: None

convergent

Whether the target's theory guarantees the fixpoint of a cycle.

TYPE: bool DEFAULT: False

name

How diagnostics name the target.

TYPE: str DEFAULT: ''

Source code in src/quivers/dsl/semirings/free.py
def __init__(
    self,
    semiring: ChartSemiring,
    system: DeductionSystem | None = None,
    *,
    convergent: bool = False,
    name: str = "",
) -> None:
    self.semiring = semiring
    self.system = system
    self.convergent = convergent
    self.name = name or semiring.name

zero

zero() -> Tensor

The algebra's zero.

RETURNS DESCRIPTION
Tensor

A scalar.

Source code in src/quivers/dsl/semirings/free.py
def zero(self) -> torch.Tensor:
    """The algebra's zero.

    Returns
    -------
    torch.Tensor
        A scalar.
    """
    return self.semiring.zero_like((), torch.empty(0, dtype=torch.float64))

plus

plus(left: Tensor, right: Tensor) -> Tensor

The algebra's sum.

PARAMETER DESCRIPTION
left

The values.

TYPE: Tensor

right

The values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

left ⊕ right.

Source code in src/quivers/dsl/semirings/free.py
def plus(self, left: torch.Tensor, right: torch.Tensor) -> torch.Tensor:
    """The algebra's sum.

    Parameters
    ----------
    left, right : torch.Tensor
        The values.

    Returns
    -------
    torch.Tensor
        ``left ⊕ right``.
    """
    return self.semiring.plus_pair(left, right)

times

times(left: Tensor, right: Tensor) -> Tensor

The algebra's product.

PARAMETER DESCRIPTION
left

The values.

TYPE: Tensor

right

The values.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

left ⊗ right.

Source code in src/quivers/dsl/semirings/free.py
def times(self, left: torch.Tensor, right: torch.Tensor) -> torch.Tensor:
    """The algebra's product.

    Parameters
    ----------
    left, right : torch.Tensor
        The values.

    Returns
    -------
    torch.Tensor
        ``left ⊗ right``.
    """
    return self.semiring.times(left, right)

image

image(generator: Generator, chart: FreeChart) -> Tensor

The generator's weight in the deduction's run in the algebra.

PARAMETER DESCRIPTION
generator

The generator.

TYPE: Generator

chart

The chart.

TYPE: FreeChart

RETURNS DESCRIPTION
Tensor

Its weight.

RAISES DESCRIPTION
SemiringError

If an occurrence must be read as a log weight and the chart's deduction runs in a semiring whose elements are not.

Source code in src/quivers/dsl/semirings/free.py
def image(self, generator: Generator, chart: FreeChart) -> torch.Tensor:
    """The generator's weight in the deduction's run in the algebra.

    Parameters
    ----------
    generator : Generator
        The generator.
    chart : FreeChart
        The chart.

    Returns
    -------
    torch.Tensor
        Its weight.

    Raises
    ------
    SemiringError
        If an occurrence must be read as a log weight and the chart's
        deduction runs in a semiring whose elements are not.
    """
    system = self.system if self.system is not None else chart.system
    if generator.kind == "rule":
        rule = system.rules[generator.index]
        if rule.weight_fn is None:
            return self.semiring.unit_like((), torch.empty(0))
        with _scope(system):
            return rule.weight_fn(dict(generator.bindings), (), self.semiring)
    if not self.semiring.log_weights:
        return self.semiring.unit_like((), torch.empty(0))
    if not system.semiring.log_weights:
        raise SemiringError(
            f"the inputs of deduction {chart.deduction!r} are weighed in "
            f"{system.semiring.name}, whose elements are not log weights, so "
            f"they have no image in {self.semiring.name}; run the deduction in "
            "a log-weight instance or make it generic",
            0,
            0,
        )
    weights = (
        chart.axiom_weights
        if system is chart.system
        else chart_inputs(system, chart)
    )
    return weights[generator.index]

same

same(left: Tensor, right: Tensor) -> bool

Exact equality of two values.

PARAMETER DESCRIPTION
left

The values.

TYPE: Tensor

right

The values.

TYPE: Tensor

RETURNS DESCRIPTION
bool

Whether they are equal.

Source code in src/quivers/dsl/semirings/free.py
def same(self, left: torch.Tensor, right: torch.Tensor) -> bool:
    """Exact equality of two values.

    Parameters
    ----------
    left, right : torch.Tensor
        The values.

    Returns
    -------
    bool
        Whether they are equal.
    """
    return bool(torch.equal(left, right))

FreeChart didactic-model

FreeChart(*, deduction: str, system: DeductionSystem = field(opaque=True, extras=OPAQUE_BY_IDENTITY), items: tuple[Item, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), edges: dict[Item, tuple[FreeEdge, ...]] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), goals: tuple[Item, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), order: tuple[Item, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), axiom_weights: tuple[Tensor, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY), input: HeldValue = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A deduction's chart in the free instance: its derivation hypergraph.

PARAMETER DESCRIPTION
deduction

The deduction's name.

TYPE: str

system

The compiled deduction the chart was computed from.

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

items

Every derived item, in the order found.

TYPE: tuple of Item DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

edges

The edges concluding each item.

TYPE: dict of Item to tuple of FreeEdge DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

goals

The goal items.

TYPE: tuple of Item DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

order

The items with every premise before its conclusions, or None when the hypergraph has a cycle.

TYPE: tuple of Item or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

axiom_weights

The weight of each input occurrence in the deduction's own semiring, in input order.

TYPE: tuple of torch.Tensor DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY)

input

The input the chart was computed from.

TYPE: HeldValue DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

acyclic property

acyclic: bool

Whether every item has finitely many derivations.

RETURNS DESCRIPTION
bool

True when the hypergraph has no cycle.

FreeEdge didactic-model

FreeEdge(*, generator: Generator = field(opaque=True, extras=OPAQUE_BY_VALUE), premises: tuple[Item, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

One way an item is derived: a generator and the premises it combines.

PARAMETER DESCRIPTION
generator

The input occurrence or rule instance.

TYPE: Generator DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

premises

The premise items in premise order; none for an occurrence.

TYPE: tuple of Item DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY)

FreeHomomorphism

FreeHomomorphism(limit: int = MAX_MONOMIALS)

Bases: Homomorphism[Polynomial]

The identity on the free instance: values are polynomials.

PARAMETER DESCRIPTION
limit

The most monomials a value may have.

TYPE: int DEFAULT: MAX_MONOMIALS

Source code in src/quivers/dsl/semirings/free.py
def __init__(self, limit: int = MAX_MONOMIALS) -> None:
    self.limit = limit
    self.name = "the free commutative semiring"

zero

zero() -> Polynomial

The zero polynomial.

RETURNS DESCRIPTION
Polynomial

No monomials.

Source code in src/quivers/dsl/semirings/free.py
def zero(self) -> Polynomial:
    """The zero polynomial.

    Returns
    -------
    Polynomial
        No monomials.
    """
    return {}

plus

plus(left: Polynomial, right: Polynomial) -> Polynomial

The sum of two polynomials.

PARAMETER DESCRIPTION
left

The polynomials.

TYPE: Polynomial

right

The polynomials.

TYPE: Polynomial

RETURNS DESCRIPTION
Polynomial

Their sum.

Source code in src/quivers/dsl/semirings/free.py
def plus(self, left: Polynomial, right: Polynomial) -> Polynomial:
    """The sum of two polynomials.

    Parameters
    ----------
    left, right : Polynomial
        The polynomials.

    Returns
    -------
    Polynomial
        Their sum.
    """
    total = Counter(left)
    total.update(right)
    return self._bounded(dict(total))

times

times(left: Polynomial, right: Polynomial) -> Polynomial

The product of two polynomials.

PARAMETER DESCRIPTION
left

The polynomials.

TYPE: Polynomial

right

The polynomials.

TYPE: Polynomial

RETURNS DESCRIPTION
Polynomial

Their product.

Source code in src/quivers/dsl/semirings/free.py
def times(self, left: Polynomial, right: Polynomial) -> Polynomial:
    """The product of two polynomials.

    Parameters
    ----------
    left, right : Polynomial
        The polynomials.

    Returns
    -------
    Polynomial
        Their product.
    """
    total: Counter[Monomial] = Counter()
    for a, x in left.items():
        for b, y in right.items():
            exponents = Counter(dict(a))
            exponents.update(dict(b))
            total[tuple(sorted(exponents.items()))] += x * y
    return self._bounded(dict(total))

image

image(generator: Generator, chart: FreeChart) -> Polynomial

The generator as a polynomial.

PARAMETER DESCRIPTION
generator

The generator.

TYPE: Generator

chart

The chart.

TYPE: FreeChart

RETURNS DESCRIPTION
Polynomial

The monomial of the generator.

Source code in src/quivers/dsl/semirings/free.py
def image(self, generator: Generator, chart: FreeChart) -> Polynomial:
    """The generator as a polynomial.

    Parameters
    ----------
    generator : Generator
        The generator.
    chart : FreeChart
        The chart.

    Returns
    -------
    Polynomial
        The monomial of the generator.
    """
    return {((generator.key, 1),): 1}

same

same(left: Polynomial, right: Polynomial) -> bool

Equality of polynomials.

PARAMETER DESCRIPTION
left

The polynomials.

TYPE: Polynomial

right

The polynomials.

TYPE: Polynomial

RETURNS DESCRIPTION
bool

Whether they have the same monomials and coefficients.

Source code in src/quivers/dsl/semirings/free.py
def same(self, left: Polynomial, right: Polynomial) -> bool:
    """Equality of polynomials.

    Parameters
    ----------
    left, right : Polynomial
        The polynomials.

    Returns
    -------
    bool
        Whether they have the same monomials and coefficients.
    """
    return left == right

Generator didactic-model

Generator(*, kind: Literal['axiom', 'rule'], index: int, rule: str = '', bindings: Bindings = field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A variable of the free semiring: an input occurrence or a rule instance.

PARAMETER DESCRIPTION
kind

"axiom" or "rule".

TYPE: str

index

The occurrence's position among the run's inputs, or the rule's position among the deduction's rules.

TYPE: int

rule

The rule's name; empty for an occurrence.

TYPE: str DEFAULT: ''

bindings

The rule instance's variables; empty for an occurrence.

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

key property

key: tuple[str, int, Bindings]

What tells one variable from another.

RETURNS DESCRIPTION
tuple

The kind, the index, and the bindings.

Homomorphism

Bases: ABC

A semiring and where each generator of a free chart goes in it.

The values are of any type V; an algebra of quivers.core.algebras holds tensors, a finite model its elements.

name class-attribute instance-attribute

name: str = ''

How diagnostics name the target.

convergent class-attribute instance-attribute

convergent: bool = False

Whether the target's theory guarantees the fixpoint of a cycle.

zero abstractmethod

zero() -> V

The sum over no derivations.

RETURNS DESCRIPTION
V

The additive unit.

Source code in src/quivers/dsl/semirings/free.py
@abstractmethod
def zero(self) -> V:
    """The sum over no derivations.

    Returns
    -------
    V
        The additive unit.
    """
    ...

plus abstractmethod

plus(left: V, right: V) -> V

The sum of two values.

PARAMETER DESCRIPTION
left

The values.

TYPE: V

right

The values.

TYPE: V

RETURNS DESCRIPTION
V

left + right.

Source code in src/quivers/dsl/semirings/free.py
@abstractmethod
def plus(self, left: V, right: V) -> V:
    """The sum of two values.

    Parameters
    ----------
    left, right : V
        The values.

    Returns
    -------
    V
        ``left + right``.
    """
    ...

times abstractmethod

times(left: V, right: V) -> V

The product of two values.

PARAMETER DESCRIPTION
left

The values.

TYPE: V

right

The values.

TYPE: V

RETURNS DESCRIPTION
V

left * right.

Source code in src/quivers/dsl/semirings/free.py
@abstractmethod
def times(self, left: V, right: V) -> V:
    """The product of two values.

    Parameters
    ----------
    left, right : V
        The values.

    Returns
    -------
    V
        ``left * right``.
    """
    ...

image abstractmethod

image(generator: Generator, chart: FreeChart) -> V

Where a generator goes.

PARAMETER DESCRIPTION
generator

The generator.

TYPE: Generator

chart

The chart it is a generator of.

TYPE: FreeChart

RETURNS DESCRIPTION
V

Its image.

Source code in src/quivers/dsl/semirings/free.py
@abstractmethod
def image(self, generator: Generator, chart: FreeChart) -> V:
    """Where a generator goes.

    Parameters
    ----------
    generator : Generator
        The generator.
    chart : FreeChart
        The chart it is a generator of.

    Returns
    -------
    V
        Its image.
    """
    ...

same abstractmethod

same(left: V, right: V) -> bool

Whether two values are equal, which decides when iteration stops.

PARAMETER DESCRIPTION
left

The values.

TYPE: V

right

The values.

TYPE: V

RETURNS DESCRIPTION
bool

Their equality.

Source code in src/quivers/dsl/semirings/free.py
@abstractmethod
def same(self, left: V, right: V) -> bool:
    """Whether two values are equal, which decides when iteration stops.

    Parameters
    ----------
    left, right : V
        The values.

    Returns
    -------
    bool
        Their equality.
    """
    ...

ModelHomomorphism

ModelHomomorphism(model: CheckedModel, images: Callable[[Generator], Value], *, convergent: bool = False)

Bases: Homomorphism[Value]

The homomorphism into a finite model of a semiring theory.

PARAMETER DESCRIPTION
model

A model of a theory that includes std.semiring's Semiring, checked against its laws.

TYPE: CheckedModel

images

Where each generator goes, an element of the model's carrier.

TYPE: Callable

convergent

Whether the model's theory guarantees the fixpoint of a cycle.

TYPE: bool DEFAULT: False

Source code in src/quivers/dsl/semirings/free.py
def __init__(
    self,
    model: CheckedModel,
    images: Callable[[Generator], FiniteValue],
    *,
    convergent: bool = False,
) -> None:
    self.model = model
    self.images = images
    self.convergent = convergent
    self.name = model.name

zero

zero() -> Value

The model's zero.

RETURNS DESCRIPTION
Value

zero().

Source code in src/quivers/dsl/semirings/free.py
def zero(self) -> FiniteValue:
    """The model's zero.

    Returns
    -------
    FiniteValue
        ``zero()``.
    """
    return self._apply("zero")

plus

plus(left: Value, right: Value) -> Value

The model's sum.

PARAMETER DESCRIPTION
left

The values.

TYPE: Value

right

The values.

TYPE: Value

RETURNS DESCRIPTION
Value

plus(left, right).

Source code in src/quivers/dsl/semirings/free.py
def plus(self, left: FiniteValue, right: FiniteValue) -> FiniteValue:
    """The model's sum.

    Parameters
    ----------
    left, right : FiniteValue
        The values.

    Returns
    -------
    FiniteValue
        ``plus(left, right)``.
    """
    return self._apply("plus", left, right)

times

times(left: Value, right: Value) -> Value

The model's product.

PARAMETER DESCRIPTION
left

The values.

TYPE: Value

right

The values.

TYPE: Value

RETURNS DESCRIPTION
Value

times(left, right).

Source code in src/quivers/dsl/semirings/free.py
def times(self, left: FiniteValue, right: FiniteValue) -> FiniteValue:
    """The model's product.

    Parameters
    ----------
    left, right : FiniteValue
        The values.

    Returns
    -------
    FiniteValue
        ``times(left, right)``.
    """
    return self._apply("times", left, right)

image

image(generator: Generator, chart: FreeChart) -> Value

The model element the generator is sent to.

PARAMETER DESCRIPTION
generator

The generator.

TYPE: Generator

chart

The chart.

TYPE: FreeChart

RETURNS DESCRIPTION
Value

Its image.

Source code in src/quivers/dsl/semirings/free.py
def image(self, generator: Generator, chart: FreeChart) -> FiniteValue:
    """The model element the generator is sent to.

    Parameters
    ----------
    generator : Generator
        The generator.
    chart : FreeChart
        The chart.

    Returns
    -------
    FiniteValue
        Its image.
    """
    return self.images(generator)

same

same(left: Value, right: Value) -> bool

Equality of two model elements.

PARAMETER DESCRIPTION
left

The values.

TYPE: Value

right

The values.

TYPE: Value

RETURNS DESCRIPTION
bool

Whether they are equal.

Source code in src/quivers/dsl/semirings/free.py
def same(self, left: FiniteValue, right: FiniteValue) -> bool:
    """Equality of two model elements.

    Parameters
    ----------
    left, right : FiniteValue
        The values.

    Returns
    -------
    bool
        Whether they are equal.
    """
    return left == right

ProductHomomorphism

ProductHomomorphism(left: Homomorphism[A], right: Homomorphism[B])

Bases: Homomorphism[tuple[A, B]]

The pairing of two homomorphisms: a homomorphism into the product.

PARAMETER DESCRIPTION
left

The first component.

TYPE: Homomorphism

right

The second component.

TYPE: Homomorphism

Source code in src/quivers/dsl/semirings/free.py
def __init__(self, left: Homomorphism[A], right: Homomorphism[B]) -> None:
    self.left = left
    self.right = right
    self.name = f"{left.name} * {right.name}"
    self.convergent = left.convergent and right.convergent

zero

zero() -> tuple[A, B]

The pair of zeros.

RETURNS DESCRIPTION
tuple

Each component's zero.

Source code in src/quivers/dsl/semirings/free.py
def zero(self) -> tuple[A, B]:
    """The pair of zeros.

    Returns
    -------
    tuple
        Each component's zero.
    """
    return (self.left.zero(), self.right.zero())

plus

plus(left: tuple[A, B], right: tuple[A, B]) -> tuple[A, B]

The componentwise sum.

PARAMETER DESCRIPTION
left

The pairs.

TYPE: tuple

right

The pairs.

TYPE: tuple

RETURNS DESCRIPTION
tuple

The pair of sums.

Source code in src/quivers/dsl/semirings/free.py
def plus(self, left: tuple[A, B], right: tuple[A, B]) -> tuple[A, B]:
    """The componentwise sum.

    Parameters
    ----------
    left, right : tuple
        The pairs.

    Returns
    -------
    tuple
        The pair of sums.
    """
    return (
        self.left.plus(left[0], right[0]),
        self.right.plus(left[1], right[1]),
    )

times

times(left: tuple[A, B], right: tuple[A, B]) -> tuple[A, B]

The componentwise product.

PARAMETER DESCRIPTION
left

The pairs.

TYPE: tuple

right

The pairs.

TYPE: tuple

RETURNS DESCRIPTION
tuple

The pair of products.

Source code in src/quivers/dsl/semirings/free.py
def times(self, left: tuple[A, B], right: tuple[A, B]) -> tuple[A, B]:
    """The componentwise product.

    Parameters
    ----------
    left, right : tuple
        The pairs.

    Returns
    -------
    tuple
        The pair of products.
    """
    return (
        self.left.times(left[0], right[0]),
        self.right.times(left[1], right[1]),
    )

image

image(generator: Generator, chart: FreeChart) -> tuple[A, B]

The pair of images.

PARAMETER DESCRIPTION
generator

The generator.

TYPE: Generator

chart

The chart.

TYPE: FreeChart

RETURNS DESCRIPTION
tuple

Each component's image.

Source code in src/quivers/dsl/semirings/free.py
def image(self, generator: Generator, chart: FreeChart) -> tuple[A, B]:
    """The pair of images.

    Parameters
    ----------
    generator : Generator
        The generator.
    chart : FreeChart
        The chart.

    Returns
    -------
    tuple
        Each component's image.
    """
    return (self.left.image(generator, chart), self.right.image(generator, chart))

same

same(left: tuple[A, B], right: tuple[A, B]) -> bool

Componentwise equality.

PARAMETER DESCRIPTION
left

The pairs.

TYPE: tuple

right

The pairs.

TYPE: tuple

RETURNS DESCRIPTION
bool

Whether both components are equal.

Source code in src/quivers/dsl/semirings/free.py
def same(self, left: tuple[A, B], right: tuple[A, B]) -> bool:
    """Componentwise equality.

    Parameters
    ----------
    left, right : tuple
        The pairs.

    Returns
    -------
    bool
        Whether both components are equal.
    """
    return self.left.same(left[0], right[0]) and self.right.same(left[1], right[1])

DeductionSemiringChoice didactic-model

DeductionSemiringChoice(*, instance: str | None = None, kernel: KernelSemiring | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), theory: str | None = None)

Bases: ValueModel

What a deduction's semiring parameter resolves to.

PARAMETER DESCRIPTION
instance

The flat name of the instance the deduction runs in, None for the log semiring of a header without a parameter or for a generic deduction.

TYPE: str or None DEFAULT: None

kernel

The kernel record of that instance, or of the log semiring; None for a generic deduction.

TYPE: KernelSemiring or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

theory

For a generic deduction, the flat name of the theory its instances range over.

TYPE: str or None DEFAULT: None

generic property

generic: bool

Whether the deduction ranges over the instances of a theory.

RETURNS DESCRIPTION
bool

True for [S : T].

SemiringError

SemiringError(message: str, line: int, col: int)

Bases: ValueError

A semiring instance or parameter the checker refuses.

PARAMETER DESCRIPTION
message

What is wrong, naming the instance, theory, or law.

TYPE: str

line

The source position of the offending declaration or parameter.

TYPE: int

col

The source position of the offending declaration or parameter.

TYPE: int

Source code in src/quivers/dsl/semirings/instances.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.message = message
    self.line = line
    self.col = col

CheckedSemiring didactic-model

CheckedSemiring(*, name: str, theory: str, closure: tuple[str, ...], kernel: KernelSemiring = field(opaque=True, extras=OPAQUE_BY_VALUE), laws: tuple[LawRecord, ...] = ())

Bases: ValueModel

A semiring instance and what is known of its theory's laws.

PARAMETER DESCRIPTION
name

The instance's flat name.

TYPE: str

theory

The flat name of its theory.

TYPE: str

closure

Every theory its theory includes, and the theory itself.

TYPE: tuple of str

kernel

Its algebra on its carrier.

TYPE: KernelSemiring DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

laws

One record per law of the theory.

TYPE: tuple of LawRecord DEFAULT: ()

convergent property

convergent: bool

Whether the theory guarantees the fixpoint of a cyclic deduction.

RETURNS DESCRIPTION
bool

True when it includes ClosedSemiring or OmegaContinuousSemiring.

LawRecord didactic-model

LawRecord(*, law: str, status: str, evidence: str)

Bases: Model

What is known of one law of an instance's theory.

PARAMETER DESCRIPTION
law

The law's flat name, Origin.name.

TYPE: str

status

"established" or "assumed".

TYPE: str

evidence

Why: decided on the finite carrier, proved by the algebra's claim, or assumed by the declaration after the samples it held at.

TYPE: str

cycle_reason

cycle_reason(rules: Sequence[RulePattern], slots: PositionSlots, lexical: bool) -> str | None

Why a deduction's rules may derive an item from itself, if they may.

PARAMETER DESCRIPTION
rules

The rules.

TYPE: Sequence of RulePattern

slots

Which slots of each symbol hold positions.

TYPE: PositionSlots

lexical

Whether the items are read off a sentence.

TYPE: bool

RETURNS DESCRIPTION
str or None

The rules of a cycle no measure rules out, or None when no item can be derived from itself.

Source code in src/quivers/dsl/semirings/convergence.py
def cycle_reason(
    rules: Sequence[RulePattern], slots: PositionSlots, lexical: bool
) -> str | None:
    """Why a deduction's rules may derive an item from itself, if they may.

    Parameters
    ----------
    rules : Sequence of RulePattern
        The rules.
    slots : PositionSlots
        Which slots of each symbol hold positions.
    lexical : bool
        Whether the items are read off a sentence.

    Returns
    -------
    str or None
        The rules of a cycle no measure rules out, or ``None`` when no
        item can be derived from itself.
    """
    steps = [(rule, premise) for rule in rules for premise in rule.premises]
    edges: dict[int, list[int]] = {}
    for source, (rule, _premise) in enumerate(steps):
        for target, (_other, premise) in enumerate(steps):
            if unifiable(rule.conclusion, premise):
                edges.setdefault(source, []).append(target)
    signs = [_step_signs(rule, premise, slots, lexical) for rule, premise in steps]
    found = _cycle(range(len(steps)), edges, signs, 0)
    if found is None:
        return None
    names = sorted({steps[node][0].name for node in found})
    return "rules " + ", ".join(repr(name) for name in names)

require_convergence

require_convergence(decl: DeductionDecl, slots: PositionSlots, *, convergent: bool, semiring: str) -> None

Refuse a cyclic deduction whose semiring guarantees no fixpoint.

PARAMETER DESCRIPTION
decl

The deduction.

TYPE: DeductionDecl

slots

Which slots of each symbol hold positions.

TYPE: PositionSlots

convergent

Whether its semiring's theory includes ClosedSemiring or OmegaContinuousSemiring.

TYPE: bool

semiring

The instance or theory, for the diagnostic.

TYPE: str

RAISES DESCRIPTION
SemiringError

If the rules may derive an item from itself, the semiring does not guarantee the fixpoint, and no tolerance is declared.

Source code in src/quivers/dsl/semirings/convergence.py
def require_convergence(
    decl: DeductionDecl,
    slots: PositionSlots,
    *,
    convergent: bool,
    semiring: str,
) -> None:
    """Refuse a cyclic deduction whose semiring guarantees no fixpoint.

    Parameters
    ----------
    decl : DeductionDecl
        The deduction.
    slots : PositionSlots
        Which slots of each symbol hold positions.
    convergent : bool
        Whether its semiring's theory includes ``ClosedSemiring`` or
        ``OmegaContinuousSemiring``.
    semiring : str
        The instance or theory, for the diagnostic.

    Raises
    ------
    SemiringError
        If the rules may derive an item from itself, the semiring does not
        guarantee the fixpoint, and no ``tolerance`` is declared.
    """
    if convergent or find_option(decl.options, STOP_OPTION) is not None:
        return
    rules = rule_patterns(decl)
    lexical = has_lexicon(decl) and all(rule.premises for rule in rules)
    reason = cycle_reason(rules, slots, lexical)
    if reason is None:
        return
    raise SemiringError(
        f"deduction {decl.name!r} may derive an item from itself ({reason} form a "
        f"cycle), and {semiring} guarantees no fixpoint of a cycle; run it in an "
        "instance of std.semiring.ClosedSemiring or "
        "std.semiring.OmegaContinuousSemiring, or declare how its iteration "
        f"stops with `{STOP_OPTION}=...`",
        decl.line,
        decl.col,
    )

rule_patterns

rule_patterns(decl: DeductionDecl) -> tuple[RulePattern, ...]

A deduction's rules as patterns, read from the declaration.

PARAMETER DESCRIPTION
decl

The deduction.

TYPE: DeductionDecl

RETURNS DESCRIPTION
tuple of RulePattern

One per rule, in order.

Source code in src/quivers/dsl/semirings/convergence.py
def rule_patterns(decl: DeductionDecl) -> tuple[RulePattern, ...]:
    """A deduction's rules as patterns, read from the declaration.

    Parameters
    ----------
    decl : DeductionDecl
        The deduction.

    Returns
    -------
    tuple of RulePattern
        One per rule, in order.
    """
    atoms = frozenset(decl.atoms)
    fresh = [0]
    return tuple(
        RulePattern(
            name=rule.name,
            premises=tuple(
                _pattern(premise, atoms, fresh) for premise in rule.premises
            ),
            conclusion=_pattern(rule.conclusion, atoms, fresh),
        )
        for rule in decl.rules
    )

unifiable

unifiable(left: Pattern, right: Pattern) -> bool

Whether two patterns have a common instance.

PARAMETER DESCRIPTION
left

The patterns.

TYPE: Pattern

right

The patterns.

TYPE: Pattern

RETURNS DESCRIPTION
bool

True when they unify with their variables renamed apart.

Source code in src/quivers/dsl/semirings/convergence.py
def unifiable(left: Pattern, right: Pattern) -> bool:
    """Whether two patterns have a common instance.

    Parameters
    ----------
    left, right : Pattern
        The patterns.

    Returns
    -------
    bool
        True when they unify with their variables renamed apart.
    """
    return _unify(_renamed(left, 0), _renamed(right, 1), {})

chart_inputs

chart_inputs(system: DeductionSystem, chart: FreeChart) -> tuple[Tensor, ...]

A deduction's weights of a free chart's input occurrences.

PARAMETER DESCRIPTION
system

The deduction, with the same rules and inputs as the chart's.

TYPE: DeductionSystem

chart

The chart.

TYPE: FreeChart

RETURNS DESCRIPTION
tuple of torch.Tensor

The weight of each occurrence in the deduction's semiring.

Source code in src/quivers/dsl/semirings/free.py
def chart_inputs(system: DeductionSystem, chart: FreeChart) -> tuple[torch.Tensor, ...]:
    """A deduction's weights of a free chart's input occurrences.

    Parameters
    ----------
    system : DeductionSystem
        The deduction, with the same rules and inputs as the chart's.
    chart : FreeChart
        The chart.

    Returns
    -------
    tuple of torch.Tensor
        The weight of each occurrence in the deduction's semiring.
    """
    return tuple(weight for _, weight in system.axiom_injector(chart.input))

evaluate

evaluate(value: Polynomial, chart: FreeChart, target: Homomorphism[V]) -> V

Apply a homomorphism to a polynomial.

PARAMETER DESCRIPTION
value

An element of the free semiring of a chart's generators.

TYPE: Polynomial

chart

The chart whose generators it is over.

TYPE: FreeChart

target

The homomorphism.

TYPE: Homomorphism

RETURNS DESCRIPTION
V

The sum over monomials of their coefficient times the product of their generators' images.

Source code in src/quivers/dsl/semirings/free.py
def evaluate[V](value: Polynomial, chart: FreeChart, target: Homomorphism[V]) -> V:
    """Apply a homomorphism to a polynomial.

    Parameters
    ----------
    value : Polynomial
        An element of the free semiring of a chart's generators.
    chart : FreeChart
        The chart whose generators it is over.
    target : Homomorphism
        The homomorphism.

    Returns
    -------
    V
        The sum over monomials of their coefficient times the product of
        their generators' images.
    """
    generators: dict[tuple[str, int, Bindings], Generator] = {
        edge.generator.key: edge.generator
        for item_edges in chart.edges.values()
        for edge in item_edges
    }
    total = target.zero()
    for monomial, coefficient in value.items():
        term: V | None = None
        for key, exponent in monomial:
            image = target.image(generators[key], chart)
            for _ in range(exponent):
                term = image if term is None else target.times(term, image)
        assert term is not None
        for _ in range(coefficient):
            total = target.plus(total, term)
    return total

free_chart

free_chart(system: DeductionSystem, input_value: HeldValue, *, name: str = '') -> FreeChart

Compute a deduction's chart in the free instance.

PARAMETER DESCRIPTION
system

The compiled deduction (Program.deductions).

TYPE: DeductionSystem

input_value

Its input: the tokens of a sentence, or its axioms.

TYPE: HeldValue

name

The deduction's name, for diagnostics; the system's by default.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
FreeChart

The derivation hypergraph, its goals, and the input occurrences' weights in the deduction's own semiring.

Source code in src/quivers/dsl/semirings/free.py
def free_chart(
    system: DeductionSystem, input_value: HeldValue, *, name: str = ""
) -> FreeChart:
    """Compute a deduction's chart in the free instance.

    Parameters
    ----------
    system : DeductionSystem
        The compiled deduction (`Program.deductions`).
    input_value : HeldValue
        Its input: the tokens of a sentence, or its axioms.
    name : str
        The deduction's name, for diagnostics; the system's by default.

    Returns
    -------
    FreeChart
        The derivation hypergraph, its goals, and the input occurrences'
        weights in the deduction's own semiring.
    """
    injected = system.axiom_injector(input_value)
    unit = BOOLEAN.unit_like((), torch.empty(0))
    recognizer = system.with_(
        semiring=BOOLEAN,
        axiom_injector=lambda value: [(item, unit) for item, _ in injected],
        tolerance=0.0,
    )
    result = recognizer.run(input_value)
    edges: dict[Item, list[FreeEdge]] = {}
    found: list[Item] = []
    seen: set[Item] = set()

    def reach(item: Item) -> None:
        if item not in seen:
            seen.add(item)
            found.append(item)

    for position, item in enumerate(result.axiom_occurrences):
        edges.setdefault(item, []).append(
            FreeEdge(
                generator=Generator(kind="axiom", index=position, bindings=()),
                premises=(),
            )
        )
        reach(item)
    for index, rule_name, antecedents, conclusion in result.applications:
        edges.setdefault(conclusion, []).append(
            FreeEdge(
                generator=Generator(
                    kind="rule",
                    index=index,
                    rule=rule_name,
                    bindings=_bindings(system, index, antecedents, conclusion),
                ),
                premises=antecedents,
            )
        )
        for premise in antecedents:
            reach(premise)
        reach(conclusion)
    frozen = {item: tuple(item_edges) for item, item_edges in edges.items()}
    chart = FreeChart(
        deduction=name or system.name,
        system=system,
        items=tuple(found),
        edges=frozen,
        goals=tuple(item for item, _ in result.goal_items),
        order=_order(found, frozen),
        axiom_weights=tuple(weight for _, weight in injected),
        input=input_value,
    )
    return chart

goal_value

goal_value(chart: FreeChart, target: Homomorphism[V], *, height: int | None = None) -> V

The goal's value along a homomorphism: the sum over the goal items.

PARAMETER DESCRIPTION
chart

The chart.

TYPE: FreeChart

target

The target.

TYPE: Homomorphism

height

A bound on the height of derivations, as specialize takes it.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
V

The sum of the goal items' values, the zero without one.

Source code in src/quivers/dsl/semirings/free.py
def goal_value[V](
    chart: FreeChart, target: Homomorphism[V], *, height: int | None = None
) -> V:
    """The goal's value along a homomorphism: the sum over the goal items.

    Parameters
    ----------
    chart : FreeChart
        The chart.
    target : Homomorphism
        The target.
    height : int or None
        A bound on the height of derivations, as `specialize` takes it.

    Returns
    -------
    V
        The sum of the goal items' values, the zero without one.
    """
    values = specialize(chart, target, height=height)
    return _sum([values[goal] for goal in chart.goals if goal in values], target)

homomorphism

homomorphism(target: CheckedSemiring | ChartSemiring, system: DeductionSystem | None = None) -> AlgebraHomomorphism

The homomorphism into an instance that a deduction's run defines.

PARAMETER DESCRIPTION
target

A checked instance (from Program.semirings) or a chart semiring.

TYPE: CheckedSemiring or ChartSemiring

system

The deduction whose weights the generators go to; the chart's own deduction when None.

TYPE: DeductionSystem or None DEFAULT: None

RETURNS DESCRIPTION
AlgebraHomomorphism

The homomorphism.

Source code in src/quivers/dsl/semirings/free.py
def homomorphism(
    target: CheckedSemiring | ChartSemiring, system: DeductionSystem | None = None
) -> AlgebraHomomorphism:
    """The homomorphism into an instance that a deduction's run defines.

    Parameters
    ----------
    target : CheckedSemiring or ChartSemiring
        A checked instance (from `Program.semirings`) or a chart semiring.
    system : DeductionSystem or None
        The deduction whose weights the generators go to; the chart's own
        deduction when ``None``.

    Returns
    -------
    AlgebraHomomorphism
        The homomorphism.
    """
    if isinstance(target, CheckedSemiring):
        return AlgebraHomomorphism(
            chart_semiring(target.kernel.member),
            system,
            convergent=target.convergent,
            name=target.name,
        )
    return AlgebraHomomorphism(target, system)

joint

joint(left: tuple[DeductionSystem, CheckedSemiring | ChartSemiring], right: tuple[DeductionSystem, CheckedSemiring | ChartSemiring], input_value: HeldValue, *, height: int | None = None) -> tuple[Tensor, Tensor]

Run two deductions over one input in one pass, in the product of their semirings.

The two deductions must have the same rules and read the same input occurrences off the input, so they share one derivation hypergraph; each component is weighed by its own deduction, in its own instance.

PARAMETER DESCRIPTION
left

Each deduction's compiled system and the instance it runs in.

TYPE: tuple

right

Each deduction's compiled system and the instance it runs in.

TYPE: tuple

input_value

The input.

TYPE: HeldValue

height

A bound on the height of derivations, as specialize takes it.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
tuple of torch.Tensor

The goal's value in each deduction's instance.

RAISES DESCRIPTION
SemiringError

If the deductions do not share a derivation hypergraph.

Source code in src/quivers/dsl/semirings/free.py
def joint[A, B](
    left: tuple[DeductionSystem, CheckedSemiring | ChartSemiring],
    right: tuple[DeductionSystem, CheckedSemiring | ChartSemiring],
    input_value: HeldValue,
    *,
    height: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Run two deductions over one input in one pass, in the product of their semirings.

    The two deductions must have the same rules and read the same input
    occurrences off the input, so they share one derivation hypergraph;
    each component is weighed by its own deduction, in its own instance.

    Parameters
    ----------
    left, right : tuple
        Each deduction's compiled system and the instance it runs in.
    input_value : HeldValue
        The input.
    height : int or None
        A bound on the height of derivations, as `specialize` takes it.

    Returns
    -------
    tuple of torch.Tensor
        The goal's value in each deduction's instance.

    Raises
    ------
    SemiringError
        If the deductions do not share a derivation hypergraph.
    """
    left_system, left_target = left
    right_system, right_target = right
    reason = same_rules(left_system, right_system)
    if reason is None and [
        item for item, _ in left_system.axiom_injector(input_value)
    ] != [item for item, _ in right_system.axiom_injector(input_value)]:
        reason = "they read different input occurrences off the input"
    if reason is not None:
        raise SemiringError(
            f"deductions {left_system.name!r} and {right_system.name!r} do not share "
            f"one derivation hypergraph: {reason}",
            0,
            0,
        )
    chart = free_chart(left_system, input_value)
    pairing = product(
        homomorphism(left_target, left_system), homomorphism(right_target, right_system)
    )
    return goal_value(chart, pairing, height=height)

polynomial

polynomial(chart: FreeChart, item: Item, *, limit: int = MAX_MONOMIALS) -> Polynomial

An item's value in the free commutative semiring.

PARAMETER DESCRIPTION
chart

An acyclic chart.

TYPE: FreeChart

item

The item.

TYPE: Item

limit

The most monomials the polynomial may have.

TYPE: int DEFAULT: MAX_MONOMIALS

RETURNS DESCRIPTION
Polynomial

Each monomial (a derivation's generators with their multiplicities) with the number of derivations that have it.

RAISES DESCRIPTION
SemiringError

If the chart has a cycle or the polynomial is larger than the limit.

Source code in src/quivers/dsl/semirings/free.py
def polynomial(
    chart: FreeChart, item: Item, *, limit: int = MAX_MONOMIALS
) -> Polynomial:
    """An item's value in the free commutative semiring.

    Parameters
    ----------
    chart : FreeChart
        An acyclic chart.
    item : Item
        The item.
    limit : int
        The most monomials the polynomial may have.

    Returns
    -------
    Polynomial
        Each monomial (a derivation's generators with their multiplicities)
        with the number of derivations that have it.

    Raises
    ------
    SemiringError
        If the chart has a cycle or the polynomial is larger than the limit.
    """
    if chart.order is None:
        raise SemiringError(
            f"the free chart of deduction {chart.deduction!r} has a cycle, so its "
            "items' polynomials are infinite series",
            0,
            0,
        )
    return specialize(chart, FreeHomomorphism(limit)).get(item, {})

product

product(left: Homomorphism[A], right: Homomorphism[B]) -> ProductHomomorphism[A, B]

The homomorphism into the product of two targets.

PARAMETER DESCRIPTION
left

The components.

TYPE: Homomorphism

right

The components.

TYPE: Homomorphism

RETURNS DESCRIPTION
ProductHomomorphism

Their pairing.

Source code in src/quivers/dsl/semirings/free.py
def product[A, B](
    left: Homomorphism[A], right: Homomorphism[B]
) -> ProductHomomorphism[A, B]:
    """The homomorphism into the product of two targets.

    Parameters
    ----------
    left, right : Homomorphism
        The components.

    Returns
    -------
    ProductHomomorphism
        Their pairing.
    """
    return ProductHomomorphism(left, right)

same_rules

same_rules(left: DeductionSystem, right: DeductionSystem) -> str | None

Why two deductions do not share one derivation hypergraph, if they do not.

PARAMETER DESCRIPTION
left

The compiled deductions.

TYPE: DeductionSystem

right

The compiled deductions.

TYPE: DeductionSystem

RETURNS DESCRIPTION
str or None

The first rule they differ at, or None when their rules agree in name, premises, and conclusion, position by position.

Source code in src/quivers/dsl/semirings/free.py
def same_rules(left: DeductionSystem, right: DeductionSystem) -> str | None:
    """Why two deductions do not share one derivation hypergraph, if they do not.

    Parameters
    ----------
    left, right : DeductionSystem
        The compiled deductions.

    Returns
    -------
    str or None
        The first rule they differ at, or ``None`` when their rules agree
        in name, premises, and conclusion, position by position.
    """
    if len(left.rules) != len(right.rules):
        return f"they have {len(left.rules)} and {len(right.rules)} rules"
    for mine, theirs in zip(left.rules, right.rules, strict=True):
        if (mine.name, mine.premises, mine.conclusion) != (
            theirs.name,
            theirs.premises,
            theirs.conclusion,
        ):
            return f"rule {mine.name!r} differs from rule {theirs.name!r}"
    return None

specialize

specialize(chart: FreeChart, target: Homomorphism[V], *, height: int | None = None) -> dict[Item, V]

Evaluate a free chart along a homomorphism.

PARAMETER DESCRIPTION
chart

The chart in the free instance.

TYPE: FreeChart

target

Where each generator goes, and the semiring it goes to.

TYPE: Homomorphism

height

A bound on the height of the derivations summed, an input having height one; required for a cyclic chart in a target whose theory does not guarantee the fixpoint.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
dict of Item to V

Every item's value.

RAISES DESCRIPTION
SemiringError

If the chart has a cycle, the target guarantees no fixpoint, and no height is given; or the iteration to the fixpoint does not settle within as many rounds as the chart has items.

Source code in src/quivers/dsl/semirings/free.py
def specialize[V](
    chart: FreeChart, target: Homomorphism[V], *, height: int | None = None
) -> dict[Item, V]:
    """Evaluate a free chart along a homomorphism.

    Parameters
    ----------
    chart : FreeChart
        The chart in the free instance.
    target : Homomorphism
        Where each generator goes, and the semiring it goes to.
    height : int or None
        A bound on the height of the derivations summed, an input having
        height one; required for a cyclic chart in a target whose theory
        does not guarantee the fixpoint.

    Returns
    -------
    dict of Item to V
        Every item's value.

    Raises
    ------
    SemiringError
        If the chart has a cycle, the target guarantees no fixpoint, and no
        height is given; or the iteration to the fixpoint does not settle
        within as many rounds as the chart has items.
    """
    images: dict[tuple[str, int, Bindings], V] = {}
    if height is not None:
        values: dict[Item, V] = {}
        for _ in range(height):
            values = {
                item: _sum(
                    [
                        _edge_value(edge, chart, target, values, images)
                        for edge in chart.edges.get(item, ())
                        if all(premise in values for premise in edge.premises)
                    ],
                    target,
                )
                for item in chart.items
            }
        return values
    if chart.order is not None:
        values = {}
        for item in chart.order:
            values[item] = _sum(
                [
                    _edge_value(edge, chart, target, values, images)
                    for edge in chart.edges.get(item, ())
                ],
                target,
            )
        return values
    if not target.convergent:
        raise SemiringError(
            f"the free chart of deduction {chart.deduction!r} has a cycle, and "
            f"{target.name} guarantees no fixpoint of a cycle; specialize it to an "
            "instance of ClosedSemiring or OmegaContinuousSemiring, or give a "
            "height",
            0,
            0,
        )
    values = {item: target.zero() for item in chart.items}
    for _ in range(len(chart.items) + 1):
        updated = {
            item: _sum(
                [
                    _edge_value(edge, chart, target, values, images)
                    for edge in chart.edges.get(item, ())
                ],
                target,
            )
            for item in chart.items
        }
        if all(target.same(updated[item], values[item]) for item in chart.items):
            return updated
        values = updated
    raise SemiringError(
        f"the free chart of deduction {chart.deduction!r} did not reach its fixpoint "
        f"in {target.name} within {len(chart.items) + 1} rounds",
        0,
        0,
    )

declared_instances

declared_instances(statements: Sequence[object]) -> dict[str, SemiringDecl]

Every semiring instance a flat program declares, by its flat name.

PARAMETER DESCRIPTION
statements

The program's statements.

TYPE: Sequence of object

RETURNS DESCRIPTION
dict of str to SemiringDecl

The instances.

Source code in src/quivers/dsl/semirings/instances.py
def declared_instances(statements: Sequence[object]) -> dict[str, SemiringDecl]:
    """Every semiring instance a flat program declares, by its flat name.

    Parameters
    ----------
    statements : Sequence of object
        The program's statements.

    Returns
    -------
    dict of str to SemiringDecl
        The instances.
    """
    return {
        statement.name: statement
        for statement in statements
        if isinstance(statement, SemiringDecl)
    }

deduction_semiring

deduction_semiring(decl: DeductionDecl, instances: Mapping[str, SemiringDecl]) -> DeductionSemiringChoice

Resolve a deduction's semiring parameter.

PARAMETER DESCRIPTION
decl

The deduction, from the flat program.

TYPE: DeductionDecl

instances

The flat program's instances, by flat name.

TYPE: Mapping of str to SemiringDecl

RETURNS DESCRIPTION
DeductionSemiringChoice

The instance and its kernel record, the theory of a generic deduction, or the log semiring without a parameter.

RAISES DESCRIPTION
SemiringError

If the deduction still gives its semiring as an option, or its parameter names no declared instance; the message lists the instances in scope.

Source code in src/quivers/dsl/semirings/instances.py
def deduction_semiring(
    decl: DeductionDecl, instances: Mapping[str, SemiringDecl]
) -> DeductionSemiringChoice:
    """Resolve a deduction's semiring parameter.

    Parameters
    ----------
    decl : DeductionDecl
        The deduction, from the flat program.
    instances : Mapping of str to SemiringDecl
        The flat program's instances, by flat name.

    Returns
    -------
    DeductionSemiringChoice
        The instance and its kernel record, the theory of a generic
        deduction, or the log semiring without a parameter.

    Raises
    ------
    SemiringError
        If the deduction still gives its semiring as an option, or its
        parameter names no declared instance; the message lists the
        instances in scope.
    """
    refuse_option(decl)
    parameter = decl.semiring
    if parameter is None:
        return DeductionSemiringChoice(kernel=LOG_SEMIRING)
    if parameter.theory is not None:
        return DeductionSemiringChoice(theory=parameter.theory)
    assert parameter.instance is not None
    found = instances.get(parameter.instance)
    if found is None:
        known = ", ".join(sorted(instances)) or "none (import std.semiring)"
        raise SemiringError(
            f"deduction {decl.name!r} runs in {parameter.instance!r}, which is not "
            f"a semiring instance in scope; the instances are {known}",
            parameter.line,
            parameter.col,
        )
    return DeductionSemiringChoice(instance=found.name, kernel=kernel_of(found))

kernel_of

kernel_of(decl: SemiringDecl) -> KernelSemiring

The kernel record of an instance's algebra on its carrier.

PARAMETER DESCRIPTION
decl

The instance.

TYPE: SemiringDecl

RETURNS DESCRIPTION
KernelSemiring

The record its deductions' handlers carry.

RAISES DESCRIPTION
SemiringError

If the algebra or the carrier is not a shipped one, or the algebra's zero and unit have no element of the carrier.

Source code in src/quivers/dsl/semirings/instances.py
def kernel_of(decl: SemiringDecl) -> KernelSemiring:
    """The kernel record of an instance's algebra on its carrier.

    Parameters
    ----------
    decl : SemiringDecl
        The instance.

    Returns
    -------
    KernelSemiring
        The record its deductions' handlers carry.

    Raises
    ------
    SemiringError
        If the algebra or the carrier is not a shipped one, or the
        algebra's zero and unit have no element of the carrier.
    """
    member = ALGEBRAS.get(decl.algebra)
    if member is None:
        raise SemiringError(
            f"semiring {decl.name!r} is realized by the algebra {decl.algebra!r}, "
            f"which is not a shipped semiring with a scalar carrier; the algebras "
            f"are {', '.join(sorted(ALGEBRAS))}",
            decl.line,
            decl.col,
        )
    carrier = CARRIERS.get(decl.carrier)
    if carrier is None:
        raise SemiringError(
            f"semiring {decl.name!r} holds its elements in {decl.carrier!r}, which "
            f"is not a kernel carrier; the carriers are {', '.join(CARRIERS)}",
            decl.line,
            decl.col,
        )
    try:
        return KernelSemiring.of(member, carrier)
    except (ValueError, dx.ValidationError) as error:
        raise SemiringError(
            f"semiring {decl.name!r}: {error}", decl.line, decl.col
        ) from error

refuse_option

refuse_option(decl: DeductionDecl) -> None

Refuse the semiring option, which no longer chooses a semiring.

PARAMETER DESCRIPTION
decl

The deduction.

TYPE: DeductionDecl

RAISES DESCRIPTION
SemiringError

If the option block holds a semiring entry; the message gives the header parameter to write instead.

Source code in src/quivers/dsl/semirings/instances.py
def refuse_option(decl: DeductionDecl) -> None:
    """Refuse the ``semiring`` option, which no longer chooses a semiring.

    Parameters
    ----------
    decl : DeductionDecl
        The deduction.

    Raises
    ------
    SemiringError
        If the option block holds a ``semiring`` entry; the message gives
        the header parameter to write instead.
    """
    entry: OptionEntry | None = next(
        (item for item in decl.options if item.key == CUT_OPTION), None
    )
    if entry is None:
        return
    value = entry.value.value if isinstance(entry.value, OptionName) else "X"
    raise SemiringError(
        f"deduction {decl.name!r}: a deduction's semiring is a header parameter, "
        f"not an option; write `deduction {decl.name}[S = std.semiring.{value}]` "
        "after `import std.semiring`",
        entry.line or decl.line,
        entry.col or decl.col,
    )

check_instance

check_instance(decl: SemiringDecl, theory: TheoryValue) -> CheckedSemiring

Check a semiring instance against every law of its theory.

PARAMETER DESCRIPTION
decl

The instance, from the flat program.

TYPE: SemiringDecl

theory

Its theory, from the theory layer.

TYPE: TheoryValue

RETURNS DESCRIPTION
CheckedSemiring

The instance with a record per law.

RAISES DESCRIPTION
SemiringError

If the theory does not include std.semiring's Semiring, has an operation the algebra does not interpret, or a law is refuted at a sample, neither established nor assumed, or assumed although established; or the closure has no value at a sample.

Source code in src/quivers/dsl/semirings/laws.py
def check_instance(decl: SemiringDecl, theory: TheoryValue) -> CheckedSemiring:
    """Check a semiring instance against every law of its theory.

    Parameters
    ----------
    decl : SemiringDecl
        The instance, from the flat program.
    theory : TheoryValue
        Its theory, from the theory layer.

    Returns
    -------
    CheckedSemiring
        The instance with a record per law.

    Raises
    ------
    SemiringError
        If the theory does not include ``std.semiring``'s ``Semiring``, has
        an operation the algebra does not interpret, or a law is refuted at
        a sample, neither established nor assumed, or assumed although
        established; or the closure has no value at a sample.
    """
    key = (
        decl.model_dump_json(),
        theory.name,
        tuple(theory.closure),
        tuple(
            (member.kind, member.name, json.dumps(law_terms(theory, member.name)))
            if member.kind in ("eq", "rule")
            else (member.kind, member.name, "")
            for member in theory.members
        ),
    )
    found = _CHECKED.get(key)
    if found is None:
        found = _check_instance(decl, theory)
        _CHECKED[key] = found
    return found

convergent

convergent(value: TheoryValue) -> bool

Whether a theory guarantees the fixpoint of a cyclic deduction.

PARAMETER DESCRIPTION
value

The theory.

TYPE: TheoryValue

RETURNS DESCRIPTION
bool

True when it is or includes ClosedSemiring or OmegaContinuousSemiring, by origin.

Source code in src/quivers/dsl/semirings/laws.py
def convergent(value: TheoryValue) -> bool:
    """Whether a theory guarantees the fixpoint of a cyclic deduction.

    Parameters
    ----------
    value : TheoryValue
        The theory.

    Returns
    -------
    bool
        True when it is or includes ``ClosedSemiring`` or
        ``OmegaContinuousSemiring``, by origin.
    """
    return bool(CONVERGENT_THEORIES & {value.name, *value.closure})