Skip to content

Cyclic systems

A plan whose recursion contract is LinearCyclic and whose algebra is a Star solves its system component by component. solve builds the derived hypergraph as a packed forest, splits it into strongly connected components by components, visits them so that every premise outside a component is final first, and solves each one through the algebra's closure. Each Component records the side it was solved on.

The system of a component

Inside a component every edge must have at most one premise in the component; an edge with two is refused as nonlinear. With the products read in premise order and the rule weight last, an edge concluding \(x\) whose premise in the component is \(y\), at position \(k\), contributes

\[ a \otimes v(y) \otimes c, \qquad a = v(p_1) \otimes \cdots \otimes v(p_{k-1}), \qquad c = v(p_{k+1}) \otimes \cdots \otimes v(p_n) \otimes w_r, \]

where every \(v(p_i)\) other than \(v(y)\) is final. Whether a coefficient is the unit is decided by the rule, not by the numbers: \(a\) is the unit when \(y\) is the first premise, and \(c\) when \(y\) is the last and the rule has no weight. The remaining edges and the inputs give the constant term \(b(x)\).

Theorem (one-sided solutions). Let the algebra be a Star, whose closure \(A^* = I \oplus A \oplus A^2 \oplus \cdots\) is the sum of the weights of all paths and the least solution of \(X = I \oplus A X\) on its declared domain (Lehmann 1977). If every edge of a component has \(c\) the unit, the value of each item of the component, the sum over its derivations of their products, is \((M^* b)_x\) with \(M_{xy} = \bigoplus a\) over its edges from \(y\) to \(x\). If every edge has \(a\) the unit, it is \((b N^*)_x\) with \(N_{yx} = \bigoplus c\). Neither needs the product to commute.

Proof. In the right-linear case a derivation of \(x\) is a path \(x = x_0 \leftarrow x_1 \leftarrow \cdots \leftarrow x_m\) of edges inside the component, followed by a derivation of a term of \(b(x_m)\). Each edge's coefficient \(a\) stands to the left of the value it multiplies and its \(c\) is the unit, so the product of the derivation is \(a_1 \otimes \cdots \otimes a_m \otimes \beta\) with \(\beta\) that term's product, the coefficients in the order of the path. By distributivity, summing over the edges of each step and the terms of \(b\) gives \((M^m b)_x\) for the paths of length \(m\), and over every length \(\bigoplus_m (M^m b)_x = (M^* b)_x\), the closure's series. It solves \(v = b \oplus M v\), since \(M^* = I \oplus M M^*\). In the left-linear case each \(c\) stands to the right, the product is \(\beta \otimes c_m \otimes \cdots \otimes c_1\), and the sum is \((b N^*)_x\) by the mirror argument. QED

Outside the closure's domain the series has no value; the algebra raises, and the run is refused.

Mixed sides. A component in which some edge has \(c\) not the unit and another (or the same) has \(a\) not the unit multiplies its unknowns on both sides. With a commutative product, \(a \otimes v \otimes c = (a \otimes c) \otimes v\), and the component is right linear with \(M_{xy} = \bigoplus a \otimes c\); the record says "commuted". Without a claim that the product commutes, established by the algebra's own evidence, no one-sided system describes it, and the run is refused with mixed-sides, naming a rule multiplying on each side.

Refusals

PlanRefusal when
inadmissible the algebra does not establish the closure's least-solution law
nonlinear-cycle an edge has two premises in its own component
mixed-sides a component multiplies on both sides of a product not established to commute
divergent the closure lies outside the algebra's domain, or rounding cannot decide whether it does

A divergent closure has no value: no partial sum is returned. The cost is CYCLIC_WORK: the edges, plus \(S^3\) operations of the algebra for a component of \(S\) items, which a ring would lower to \(S^\omega\).

Parallel unary steps in a span

The span executor gives each extra parallel step in a cyclic LogProb closure its own auxiliary state. An arc of weight \(w\) from \(i\) to \(j\) becomes a step of weight \(w\) from \(i\) to that state followed by a unit step to \(j\). Every walk between original states has a unique expansion of the same weight. Conversely, a walk between original states must complete each passage through an auxiliary state. Thus the projected star sums the original walks with their multiplicities. Differentiating the projected result preserves each original coefficient's contribution on the open domain of convergence.

The star receives the primitive weights, so a sum of parallel weights near one stays inside its rounding-aware convergence check. With \(N\) categories and \(d\) extra parallel steps, the star eliminates \(N+d\) states and its input matrix holds \((N+d)^2\) elements. The span report counts the augmented pivots and algebra operations. A cyclic span plan refuses a general resource budget, whose full limits the executor does not enforce.

Monotone polynomial systems

Under MonotonePolynomial a component may have edges with several premises inside it. In an algebra with a RealEmbedding, such as MarkovAlgebra or LogProbAlgebra, each item's real value is then a polynomial with nonnegative coefficients in the component's items, \(x = f(x)\), whose coefficients carry the values of the components below. Its least fixed point \(\mu\) lies in \([0, \infty]^n\) (Etessami and Yannakakis 2009). solve_polynomial solves the components one after another by Newton's method, the decomposed method of Etessami and Yannakakis (2009, section 6), whose convergence Esparza, Kiefer and Luttenberger (2010) bound.

Theorem (lower bound). Let \(0 \le l \le \mu\), let \(J\) be the Jacobian of \(f\) at \(l\) with spectral radius below one, and let \(d\) satisfy \((I - J)\,d \le f(l) - l\). Then \(l + d \le \mu\).

Proof. Write \(\mu = l + e\) with \(e \ge 0\). A polynomial with nonnegative coefficients has \(f(l + e) \ge f(l) + J e\) (Taylor's expansion, every further term nonnegative), so \((I - J)\,e \ge f(l) - l \ge (I - J)\,d\). Since the spectral radius of \(J \ge 0\) is below one, \((I - J)^{-1} = \sum_k J^k \ge 0\), so \(e \ge d\). QED.

Each step solves \((I - J)\,d = f(l) - l\) in floating point, shortens \(d\), and then checks the two hypotheses in outward rounded arithmetic: \(J v < v\) for \(v = (I - J)^{-1} \mathbf 1 > 0\), which bounds the spectral radius below one (Collatz and Wielandt), and each row of \((I - J)\,d \le f(l) - l\), compared exactly in rationals. The coefficients enter by certified lower bounds, so the theorem holds of a system below \(f\) whose least fixed point is below \(\mu\). The iteration starts at \(l = 0\) and stops when no step moves \(l\), or when the budget's iterations are spent.

Upper bound. A point \(u\) with \(f(u) \le u\) is a pre-fixed point, and the least fixed point is the least pre-fixed point (Knaster and Tarski), so \(\mu \le u\). The candidate is \(u = e + t\,(I - J)^{-1}\mathbf 1\) above the floating estimate \(e\), for growing \(t\), checked with the coefficients' certified upper bounds. A component's interval \([l, u]\) thus holds \(\mu\), and the interval of an item above it holds its value because its coefficients' bounds come from the intervals below. The value returned is the estimate, inside its interval.

At a critical system, where the Jacobian at \(\mu\) has spectral radius one, the only pre-fixed points may be \(\mu\) itself: \(x = x^2/2 + 1/2\) has \(f(u) - u = (u - 1)^2/2\). No upper end then certifies, the run's report has no guarantee and names the spectral radius and the condition number \(\|(I - J)^{-1}\|_\infty\) at the estimate, and the contract refuses the value or returns it unestablished. A component with \(f(l) > l\) in every item has \(l < \mu\); below a finite least fixed point of a strongly connected clean system the spectral radius is below one (Esparza, Kiefer and Luttenberger 2010, section 4), so a spectral radius certified at least one there shows \(\mu\) infinite, and the plan refuses it as divergent.

Idempotent algebras. In an algebra without an embedding whose sum is idempotent, whose product commutes and which has a Star, such as TropicalAlgebra or MaxPlusAlgebra, the Newton sequence is \(\nu^{(0)} = f(0)\) and \(\nu^{(i+1)} = Df|_{\nu^{(i)}}^*\,(f(\nu^{(i)}))\) (Esparza, Kiefer and Luttenberger 2010, Newtonian program analysis, Proposition 7.1), and for a system of \(n\) variables \(\nu^{(n)} = \mu f\) (their Theorem 7.7), in the omega-continuous completion of the weights. With a commutative product \(Df|_v\) is the matrix \(J(v)\) of formal derivatives, whose repeated occurrences add to one occurrence, so each step is \(J(v)^* f(v)\) by the algebra's star on its declared domain; a star outside it is refused, so a returned value is the completion's least fixed point and lies in the carrier. Each component of \(n\) items takes \(n\) steps, and the report states the result exact; a budget that ends the steps first leaves it without a guarantee.

Derivative. At the fixed point \(x = F(x, w)\) the implicit derivative is \(dx = (I - J)^{-1}\,\partial F / \partial w \; dw\), which exists when the spectral radius at \(\mu\) is below one; the solver certifies it from \(J(u)\,v < v\), since \(J\) grows with its argument. The value is returned as \(x + (I - J)^{-1}(F - F_{\text{detached}})\), which is \(x\) and has that derivative.

References

  • Etessami, K., and Yannakakis, M. (2009). Recursive Markov chains, stochastic grammars, and monotone systems of nonlinear equations. Journal of the ACM 56(1), 1-66. doi:10.1145/1462153.1462154
  • Esparza, J., Kiefer, S., and Luttenberger, M. (2010). Newtonian program analysis. Journal of the ACM 57(6), 33:1-33:47. doi:10.1145/1857914.1857917
  • Esparza, J., Kiefer, S., and Luttenberger, M. (2010). Computing the least fixed point of positive polynomial systems. SIAM Journal on Computing 39(6), 2282-2335. doi:10.1137/090749591
  • Lehmann, D. J. (1977). Algebraic structures for transitive closure. Theoretical Computer Science 4(1), 59-76. doi:10.1016/0304-3975(77)90056-1

recursion

Cyclic systems, solved component by component: linear ones by the algebra's closure, monotone polynomial ones by decomposed Newton.

The derived hypergraph of a run is split into strongly connected components, visited so that every premise outside a component is final before the component is. Inside a component every edge has at most one premise in the component, so with the products in premise order an edge concluding x from y contributes a ⊗ v(y) ⊗ c, where a is the product of the premises before y and c that of the premises after it, then the rule weight. When every such edge has c the unit the component is right linear, v = b ⊕ M v, and its least solution is M* b; when every one has a the unit it is left linear, v = b ⊕ v N, with least solution b N* (Lehmann 1977). Neither needs the product to commute. Only a component that mixes the sides, or has an edge with both coefficients, does: with a commutative product a ⊗ v ⊗ c = (a ⊗ c) ⊗ v, and the component is right linear.

Whether a coefficient is the unit is decided by the rule, not by the numbers: a is the unit when the premise is the first, c when it is the last and the rule has no weight.

A monotone polynomial system, whose components may have edges with several premises inside them, is solved in the reals of the algebra's quivers.core.algebras.RealEmbedding by solve_polynomial: Newton's method from zero on each component keeps a certified lower bound, a pre-fixed point bounds it from above, both in outward rounded arithmetic, and the value carries the implicit derivative of the fixed point. In an algebra without an embedding whose sum is idempotent and which has a star, each component of n items is solved exactly by n Newton steps (Esparza, Kiefer and Luttenberger 2010, Newtonian program analysis, theorem 7.7).

References

Etessami, K., and Yannakakis, M. (2009). Recursive Markov chains, stochastic grammars, and monotone systems of nonlinear equations. Journal of the ACM 56(1), 1-66. doi:10.1145/1462153.1462154

Esparza, J., Kiefer, S., and Luttenberger, M. (2010). Computing the least fixed point of positive polynomial systems. SIAM Journal on Computing 39(6), 2282-2335. doi:10.1137/090749591

Esparza, J., Kiefer, S., and Luttenberger, M. (2010). Newtonian program analysis. Journal of the ACM 57(6), 33:1-33:47. doi:10.1145/1857914.1857917

Lehmann, D. J. (1977). Algebraic structures for transitive closure. Theoretical Computer Science, 4(1), 59-76. doi:10.1016/0304-3975(77)90056-1

InputId

A rule's parameter, or an input occurrence.

Side

Side = Literal['none', 'right', 'left', 'commuted']

How a component is solved: no cycle, M* b, b N*, or M* b after commuting both coefficients to the left.

CyclicRefusal

Bases: str, Enum

Why a linear cyclic system has no solution here.

CyclicRefused

CyclicRefused(code: CyclicRefusal, reason: str)

Bases: ValueError

A cyclic system is refused, with the reason.

PARAMETER DESCRIPTION
code

The kind of reason.

TYPE: CyclicRefusal

reason

The reason.

TYPE: str

Source code in src/quivers/stochastic/recursion.py
def __init__(self, code: CyclicRefusal, reason: str) -> None:
    super().__init__(f"{code.value}: {reason}")
    self.code = code
    self.reason = reason

CyclicWork didactic-model

CyclicWork(*, sums: int = 0, products: int = 0, pivots: int = 0, exact: int = 0)

Bases: QiecModel

The algebra's operations a cyclic solve performed.

PARAMETER DESCRIPTION
sums

Sums, one per element summed into another.

TYPE: int DEFAULT: 0

products

Products, one per element.

TYPE: int DEFAULT: 0

pivots

States the closures eliminated, each a closure of one element.

TYPE: int DEFAULT: 0

exact

Operations of the closures' exact or enclosed decisions.

TYPE: int DEFAULT: 0

Component didactic-model

Component(*, items: tuple[Item, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), side: Side = 'none')

Bases: QiecModel

One strongly connected component of a run and how it was solved.

PARAMETER DESCRIPTION
items

Its items.

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

side

How it was solved.

TYPE: Side DEFAULT: 'none'

Divergent

Divergent(reason: str)

Bases: ValueError

A monotone polynomial system whose least fixed point is infinite.

PARAMETER DESCRIPTION
reason

The certificate of divergence.

TYPE: str

Source code in src/quivers/stochastic/recursion.py
def __init__(self, reason: str) -> None:
    super().__init__(reason)
    self.reason = reason

NewtonComponent didactic-model

NewtonComponent(*, items: tuple[Item, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), iterations: int = 0, spectral: float | None = None, condition: float | None = None, certified: bool = False, implicit: bool = False)

Bases: QiecModel

One strongly connected component solved by Newton's method.

PARAMETER DESCRIPTION
items

Its items.

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

iterations

Newton steps taken.

TYPE: int DEFAULT: 0

spectral

An estimate of the spectral radius of the Jacobian at the solution, max_x (J s)_x / s_x for s = (I - J)^-1 1; None when it has no inverse there.

TYPE: float or None DEFAULT: None

condition

||(I - J)^-1|| in the maximum norm at the solution, max_x s_x.

TYPE: float or None DEFAULT: None

certified

Whether both ends of every item's interval were certified.

TYPE: bool DEFAULT: False

implicit

Whether the spectral radius at the upper end is certified below one, so that the implicit derivative exists.

TYPE: bool DEFAULT: False

PolynomialSolution didactic-model

PolynomialSolution(*, values: dict[Item, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), lower: dict[Item, float] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), upper: dict[Item, float] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), components: tuple[NewtonComponent, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), iterations: int = 0, sums: int = 0, products: int = 0, exact: int = 0, stopped: Literal['completed', 'budget'] = 'completed', decided: bool = False)

Bases: ValueModel

The least fixed point of a monotone polynomial system, with its enclosure.

PARAMETER DESCRIPTION
values

The value of every item in the algebra, with the implicit derivative in its inputs.

TYPE: dict of Item to torch.Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

lower

A certified lower bound of every item's real value.

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

upper

A certified upper bound, inf where none was certified.

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

components

The components, premises' components first.

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

iterations

Newton steps over all components.

TYPE: int DEFAULT: 0

sums

Sums of reals in point arithmetic.

TYPE: int DEFAULT: 0

products

Products of reals in point arithmetic.

TYPE: int DEFAULT: 0

exact

Operations in outward rounded arithmetic.

TYPE: int DEFAULT: 0

stopped

"completed" when every component's iteration stopped making progress, "budget" when the iteration budget ended it.

TYPE: str DEFAULT: 'completed'

decided

Whether the values are exact, by Newton's method in an idempotent semiring; then there are no intervals.

TYPE: bool DEFAULT: False

components

components(forest: DerivationForest) -> list[list[Item]]

The strongly connected components, premises' components first.

Tarjan's algorithm on the graph from each premise to its conclusion, without recursion. It emits a component after every component it reaches, so the reverse of its order puts premises first.

PARAMETER DESCRIPTION
forest

The derived hypergraph.

TYPE: DerivationForest

RETURNS DESCRIPTION
list of list of Item

The components, each in discovery order, premises' components before their conclusions'.

Source code in src/quivers/stochastic/recursion.py
def components(forest: DerivationForest) -> list[list[Item]]:
    """The strongly connected components, premises' components first.

    Tarjan's algorithm on the graph from each premise to its conclusion,
    without recursion. It emits a component after every component it
    reaches, so the reverse of its order puts premises first.

    Parameters
    ----------
    forest : DerivationForest
        The derived hypergraph.

    Returns
    -------
    list of list of Item
        The components, each in discovery order, premises' components
        before their conclusions'.
    """
    users: dict[Item, list[Item]] = {}
    for item in forest.items:
        for edge in forest.edges.get(item, ()):
            for premise in edge.premises:
                users.setdefault(premise, []).append(item)
    index: dict[Item, int] = {}
    low: dict[Item, int] = {}
    on_stack: set[Item] = set()
    stack: list[Item] = []
    found: list[list[Item]] = []
    counter = 0
    for root in forest.items:
        if root in index:
            continue
        work: list[tuple[Item, int]] = [(root, 0)]
        index[root] = low[root] = counter
        counter += 1
        stack.append(root)
        on_stack.add(root)
        while work:
            item, position = work[-1]
            successors = users.get(item, [])
            if position < len(successors):
                work[-1] = (item, position + 1)
                successor = successors[position]
                if successor not in index:
                    index[successor] = low[successor] = counter
                    counter += 1
                    stack.append(successor)
                    on_stack.add(successor)
                    work.append((successor, 0))
                elif successor in on_stack:
                    low[item] = min(low[item], index[successor])
                continue
            work.pop()
            if work:
                parent = work[-1][0]
                low[parent] = min(low[parent], low[item])
            if low[item] == index[item]:
                component: list[Item] = []
                while True:
                    member = stack.pop()
                    on_stack.discard(member)
                    component.append(member)
                    if member == item:
                        break
                order = {member: forest.items.index(member) for member in component}
                found.append(sorted(component, key=order.__getitem__))
    found.reverse()
    return found

solve

solve(forest: DerivationForest, algebra: OrderPreservingSemiring, inputs: Mapping[InputId, Tensor], *, like: Tensor) -> tuple[dict[Item, Tensor], tuple[Component, ...], CyclicWork]

The least solution of a linear system over a derived hypergraph.

PARAMETER DESCRIPTION
forest

The derived hypergraph, every instance and input an edge.

TYPE: DerivationForest

algebra

The algebra; it is a Star whose closure is the least solution.

TYPE: OrderPreservingSemiring

inputs

The weights.

TYPE: Mapping of InputId to torch.Tensor

like

The dtype and device of units and zeros.

TYPE: Tensor

RETURNS DESCRIPTION
tuple of dict, tuple of Component and CyclicWork

The value of every item, each component with its side, and the algebra's operations of building each component's system, closing it (as the closure reports its own work) and applying the closure to the constants.

RAISES DESCRIPTION
CyclicRefused

If an edge has two premises in its component, a component mixes the sides without a commutative product, or a closure diverges or cannot be decided.

TypeError

If the algebra has no closure.

Source code in src/quivers/stochastic/recursion.py
def solve(
    forest: DerivationForest,
    algebra: OrderPreservingSemiring,
    inputs: Mapping[InputId, torch.Tensor],
    *,
    like: torch.Tensor,
) -> tuple[dict[Item, torch.Tensor], tuple[Component, ...], CyclicWork]:
    """The least solution of a linear system over a derived hypergraph.

    Parameters
    ----------
    forest : DerivationForest
        The derived hypergraph, every instance and input an edge.
    algebra : OrderPreservingSemiring
        The algebra; it is a `Star` whose closure is the least solution.
    inputs : Mapping of InputId to torch.Tensor
        The weights.
    like : torch.Tensor
        The dtype and device of units and zeros.

    Returns
    -------
    tuple of dict, tuple of Component and CyclicWork
        The value of every item, each component with its side, and the
        algebra's operations of building each component's system, closing
        it (as the closure reports its own work) and applying the closure
        to the constants.

    Raises
    ------
    CyclicRefused
        If an edge has two premises in its component, a component mixes
        the sides without a commutative product, or a closure diverges or
        cannot be decided.
    TypeError
        If the algebra has no closure.
    """
    if not isinstance(algebra, Star):
        raise TypeError(f"{algebra.subject.name} has no closure")
    commutes = any(
        claim.law.name == TIMES_COMMUTATIVE.name and claim.established
        for claim in algebra.claims()
    )
    presentation = forest.presentation
    work = _Work(algebra)
    values: dict[Item, torch.Tensor] = {}
    solved: list[Component] = []
    for members in components(forest):
        inside = set(members)
        position = {item: index for index, item in enumerate(members)}
        constants: dict[Item, torch.Tensor] = {}
        loops: list[
            tuple[Item, Item, torch.Tensor | None, torch.Tensor | None, ForestEdge]
        ] = []
        for item in members:
            for edge in forest.edges.get(item, ()):
                weight = edge_weight(forest, edge, algebra, inputs, like=like)
                if edge.occurrence is not None:
                    constants[item] = _add(algebra, constants.get(item), weight, work)
                    continue
                places = [k for k, p in enumerate(edge.premises) if p in inside]
                if not places:
                    term = _product(
                        algebra, [*(values[p] for p in edge.premises), weight], work
                    )
                    assert term is not None
                    constants[item] = _add(algebra, constants.get(item), term, work)
                    continue
                if len(places) > 1:
                    raise CyclicRefused(
                        CyclicRefusal.NONLINEAR,
                        f"an instance of {_name(presentation, edge)} concluding "
                        f"{item.arguments} has {len(places)} premises in its own "
                        "component",
                    )
                (k,) = places
                rule = presentation.constructors_by_id[edge.constructor]
                assert isinstance(rule, Rule)
                before = _product(algebra, [values[p] for p in edge.premises[:k]], work)
                after_factors = [values[p] for p in edge.premises[k + 1 :]]
                if rule.weight is not None:
                    after_factors.append(weight)
                after = _product(algebra, after_factors, work)
                loops.append((item, edge.premises[k], before, after, edge))
        if not loops:
            for item in members:
                values[item] = constants.get(item, algebra.zero_like((), like))
            solved.append(Component(items=tuple(members), side="none"))
            continue
        side = _side(loops, commutes, presentation)
        n = len(members)
        matrix = algebra.zero_like((n, n), like)
        entries: dict[tuple[int, int], torch.Tensor] = {}
        for conclusion, premise, before, after, _ in loops:
            x, y = position[conclusion], position[premise]
            if side == "right":
                key, term = (x, y), _unit_or(algebra, before, like)
            elif side == "left":
                key, term = (y, x), _unit_or(algebra, after, like)
            else:
                key = (x, y)
                term = _times(
                    algebra,
                    _unit_or(algebra, before, like),
                    _unit_or(algebra, after, like),
                    work,
                )
            entries[key] = _add(algebra, entries.get(key), term, work)
        rows = [
            torch.stack([entries.get((i, j), matrix[i, j]) for j in range(n)])
            for i in range(n)
        ]
        filled = torch.stack(rows)
        try:
            closure, closing = algebra.star_with_work(filled)
            work.sums += closing.sums
            work.products += closing.products
            work.pivots += closing.pivots
            work.exact += closing.exact
        except DivergentClosureError as error:
            raise CyclicRefused(CyclicRefusal.DIVERGENT, str(error)) from error
        except UndecidedClosureError as error:
            raise CyclicRefused(CyclicRefusal.UNDECIDED, str(error)) from error
        zero = algebra.zero_like((), like)
        constant = [constants.get(item, zero) for item in members]
        for i, item in enumerate(members):
            total: torch.Tensor | None = None
            for j in range(n):
                if side == "left":
                    term = _times(algebra, constant[j], closure[j, i], work)
                else:
                    term = _times(algebra, closure[i, j], constant[j], work)
                total = _add(algebra, total, term, work)
            assert total is not None
            values[item] = total
        solved.append(Component(items=tuple(members), side=side))
    return (
        values,
        tuple(solved),
        CyclicWork(
            sums=work.sums,
            products=work.products,
            pivots=work.pivots,
            exact=work.exact,
        ),
    )

solve_polynomial

solve_polynomial(forest: DerivationForest, algebra: OrderPreservingSemiring, inputs: Mapping[InputId, Tensor], *, like: Tensor, budget: int | None = None) -> PolynomialSolution

The least fixed point of a monotone polynomial system, by decomposed Newton.

The derived hypergraph's strongly connected components are solved one after another, premises' components first (Etessami and Yannakakis 2009, decomposed Newton's method; Esparza, Kiefer and Luttenberger 2010 for its convergence). In the reals of the algebra's embedding, each item's value is the sum over its edges of the edge's weight times its premises' values: a polynomial with nonnegative coefficients in the component's items, whose coefficients carry the values of the components below. Each component's Newton iteration starts at zero and keeps a certified lower bound (_newton); a certified pre-fixed point bounds it from above (_upper). The bounds of a component's coefficients come from the bounds of the components below, so every interval holds the exact least fixed point. The value returned is the last iterate, inside its interval, and carries the implicit derivative (I - J)^-1 dF of the fixed point in the inputs.

In an idempotent algebra with a star and no embedding, each component of n items is solved exactly by n Newton steps instead (_idempotent).

PARAMETER DESCRIPTION
forest

The derived hypergraph, every instance and input an edge.

TYPE: DerivationForest

algebra

The algebra: a RealEmbedding, or a Star whose sum is idempotent, whose product commutes.

TYPE: OrderPreservingSemiring

inputs

The weights.

TYPE: Mapping of InputId to torch.Tensor

like

The dtype and device of units and zeros.

TYPE: Tensor

budget

The most Newton steps over all components; None for no limit.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
PolynomialSolution

The values, their intervals, and the work.

RAISES DESCRIPTION
TypeError

If the forest is not a derivation forest.

CyclicRefused

If the product is not established to commute, the algebra has neither a real embedding nor an idempotent sum with a star, or a component's least fixed point is certified infinite.

Source code in src/quivers/stochastic/recursion.py
def solve_polynomial(
    forest: DerivationForest,
    algebra: OrderPreservingSemiring,
    inputs: Mapping[InputId, torch.Tensor],
    *,
    like: torch.Tensor,
    budget: int | None = None,
) -> PolynomialSolution:
    """The least fixed point of a monotone polynomial system, by decomposed Newton.

    The derived hypergraph's strongly connected components are solved one
    after another, premises' components first (Etessami and Yannakakis
    2009, decomposed Newton's method; Esparza, Kiefer and Luttenberger
    2010 for its convergence). In the reals of the algebra's embedding,
    each item's value is the sum over its edges of the edge's weight times
    its premises' values: a polynomial with nonnegative coefficients in
    the component's items, whose coefficients carry the values of the
    components below. Each component's Newton iteration starts at zero
    and keeps a certified lower bound (`_newton`); a certified pre-fixed
    point bounds it from above (`_upper`). The bounds of a component's
    coefficients come from the bounds of the components below, so every
    interval holds the exact least fixed point. The value returned is the
    last iterate, inside its interval, and carries the implicit
    derivative ``(I - J)^-1 dF`` of the fixed point in the inputs.

    In an idempotent algebra with a star and no embedding, each component
    of ``n`` items is solved exactly by ``n`` Newton steps instead
    (`_idempotent`).

    Parameters
    ----------
    forest : DerivationForest
        The derived hypergraph, every instance and input an edge.
    algebra : OrderPreservingSemiring
        The algebra: a `RealEmbedding`, or a `Star` whose sum is idempotent,
        whose product commutes.
    inputs : Mapping of InputId to torch.Tensor
        The weights.
    like : torch.Tensor
        The dtype and device of units and zeros.
    budget : int or None
        The most Newton steps over all components; ``None`` for no limit.

    Returns
    -------
    PolynomialSolution
        The values, their intervals, and the work.

    Raises
    ------
    TypeError
        If the forest is not a derivation forest.
    CyclicRefused
        If the product is not established to commute, the algebra has
        neither a real embedding nor an idempotent sum with a star, or a
        component's least fixed point is certified infinite.
    """
    if not isinstance(forest, DerivationForest):
        raise TypeError(
            f"a monotone polynomial system is read from a derivation forest, not a "
            f"{type(forest).__name__}"
        )
    if not algebra.establishes(TIMES_COMMUTATIVE):
        raise CyclicRefused(
            CyclicRefusal.SIDES,
            "a polynomial's monomials multiply premises in any order, and the "
            "product is not established to commute",
        )
    if not isinstance(algebra, RealEmbedding):
        if isinstance(algebra, Star) and algebra.establishes(PLUS_IDEMPOTENT):
            return _idempotent(forest, algebra, inputs, like, budget)
        raise CyclicRefused(
            CyclicRefusal.NONLINEAR,
            f"{algebra.subject.name} has neither an embedding in the nonnegative "
            "reals nor an idempotent sum with a star",
        )
    rounding = algebra.embedding_rounding
    count = _Count()
    reals: dict[Item, torch.Tensor] = {}
    lower: dict[Item, float] = {}
    upper: dict[Item, float] = {}
    solved: list[NewtonComponent] = []
    stopped: Literal["completed", "budget"] = "completed"
    for members in components(forest):
        position = {item: index for index, item in enumerate(members)}
        terms: list[list[_Term]] = []
        for item in members:
            monomials: list[_Term] = []
            for edge in forest.edges.get(item, ()):
                weight = algebra.to_reals(
                    edge_weight(forest, edge, algebra, inputs, like=like)
                )
                low = high = float(weight.detach())
                for _ in range(rounding):
                    low, high = _down(low), _up(high)
                coefficient = weight
                inside: list[int] = []
                for premise in edge.premises:
                    if premise in position:
                        inside.append(position[premise])
                        continue
                    coefficient = coefficient * reals[premise]
                    low = _down(low * lower[premise])
                    high = _up(high * upper[premise])
                monomials.append(_Term(coefficient, low, high, tuple(inside)))
            terms.append(monomials)
        remaining = None if budget is None else max(budget - count.iterations, 0)
        try:
            floor, estimate, steps, exhausted = _newton(terms, count, remaining)
        except Divergent as error:
            raise CyclicRefused(CyclicRefusal.DIVERGENT, error.reason) from error
        if exhausted:
            stopped = "budget"
        ceiling, spectral, condition, implicit = _upper(terms, estimate, floor, count)
        top = ceiling if ceiling is not None else [math.inf] * len(members)
        point = [
            min(max(value, low), high)
            for value, low, high in zip(estimate, floor, top, strict=True)
        ]
        values = _implicit(terms, point)
        for index, item in enumerate(members):
            reals[item] = values[index]
            lower[item] = floor[index]
            upper[item] = top[index]
        solved.append(
            NewtonComponent(
                items=tuple(members),
                iterations=steps,
                spectral=spectral,
                condition=condition,
                certified=ceiling is not None,
                implicit=implicit,
            )
        )
    found: dict[Item, torch.Tensor] = {}
    for item, value in reals.items():
        absent = value.detach() == 0
        safe = torch.where(absent, torch.ones_like(value), value)
        found[item] = torch.where(
            absent, algebra.zero_like((), like), algebra.from_reals(safe).to(like.dtype)
        )
    return PolynomialSolution(
        values=found,
        lower=lower,
        upper=upper,
        components=tuple(solved),
        iterations=count.iterations,
        sums=count.sums,
        products=count.products,
        exact=count.exact,
        stopped=stopped,
    )