Skip to content

Contracts

A query over a rule presentation asks for one observable of the derivations of a judgment, under one interpretation of the rules. What an executor may do to answer it depends on the laws of the weight algebra, on how recursion is solved, on how accurate the answer has to be, and on what provenance is kept. The contract records state each of these as data that crosses the wire codec, and the checkers refuse every combination that does not fit, with the reason.

record what it states
QuerySpec presentation, interpretation, observable, input types, inputs of the gradient, batch axes, retention
LawClaim a law of a subject, with evidence that is proved, decided, tested or assumed
Recursion acyclic, linear cyclic, monotone polynomial, bounded by the model, or unrolled
AccuracyContract numerics, target and metric, guarantee, controls, budget, failure policy, derivative
ComplexityClaim bounds per phase and resource, each with its optimality status
WorkReport counters of the work of one phase
Retention no provenance, parent counts, requested evidence, or the packed forest
AccuracyReport what a run reached, why it stopped, what it cost, which claims it used
GroupingRecord checked reducer, row and key types, mode, exact counts, and reduction costs

Observables

Write \([\![j]\!] = \sum_{d \in D(j)} w(d) \cdot \mathrm{fold}(d)\) for the detailed meaning of a judgment \(j\): the formal sum over its derivations \(D(j)\), with \(w(d)\) the product of the axiom occurrence and rule weights. An observable is a map \(h\) from detailed meanings to results. A summary map \(s\) licenses aggregation when it preserves the sum of alternatives and commutes with every rule, and \(h\) factors through it. Each observable states what it needs:

observable laws of the algebra other needs
Support semiring, zero-sum-free, no zero divisors no derivative
Weight semiring
Best semiring, selective sum a tie rule for its derivative
KBest semiring, selective sum, superior rules a tie rule for its derivative
Outcome semiring a key computation
ProjectedWeightRows semiring an ordered field of a checked judgment
NormalizedWeightRows source weighting laws and division finitely many rows with positive total mass
WeightedProofRows ordered product with unit and absorbing zero, and associative commutative sum and division when normalized finitely many derivations for a guaranteed result
BooleanProofWeightRows semiring, and division when normalized a truth table over the ordered premises of every rule
Statistic semiring, semimodule action a statistic computation
Marginal semiring, and division when normalized
Sample semiring, division no derivative
Fold semiring, and linearity of the fold the packed forest
NonlinearFold semiring the packed forest; finitely many derivations for a guaranteed result
Forest none the packed forest; no derivative

A nonlinear fold has no summary in general: the alternatives \(-1\) and \(1\) sum to \(0\), whose square is \(0\), while their squares sum to \(2\).

Law claims

A claim's status is read from its evidence, so the two cannot disagree. Proved cites a written argument and Decided names a procedure that decides the law on the carrier: every tuple of a finite carrier, a normal form of polynomial terms, or quantifier elimination over the reals. These two are established. Tested evaluates finitely many points of a larger carrier, which can refute a law and cannot establish it, and Assumed is a declaration. An exact, certified or probabilistic result needs every law it uses to be established; a heuristic result needs every law it uses to be claimed. A claim is about the mathematical carrier: a floating point implementation satisfies no algebraic law exactly, and its rounding belongs to Numerics.

Recursion

contract solution exact by a finite method derivative
Acyclic unique, one relaxation per hyperedge yes reverse accumulation
LinearCyclic least solution \(A^* b\), needs the star law yes \(A^* \, dA \, A^*\) on the open domain of convergence
MonotonePolynomial least fixed point in the omega-continuous completion; Newton needs a real embedding (certified) or an idempotent star (exact) no: at best certified implicit, if the spectral radius of the Jacobian at the solution is below one; or unrolled
Bounded the bound is part of the model yes exact for the bounded model
Unrolled the first \(k\) iterates, a lower bound in an ordered algebra no of the \(k\) iterates and of nothing else

A bound on constructor depth or length changes the model. An iteration limit, a fuel count or a tolerance does not, and it never changes the value a query denotes.

Accuracy

The fields of an AccuracyContract are separate: a method parameter (Control) is never read as a guarantee, a ResourceBudget is never an error bound, and the derivative has its own semantics. The default is Exact with FailurePolicy.REFUSE.

A guarantee is one of: Exact, the mathematical value up to the rounding in Numerics; Certified, a bound that holds on every run; Probabilistic, a bound that fails with probability at most \(\delta\); or Heuristic. A certified bound that a run reports carries its Certificate: an outward rounded enclosure, a duality gap, an argument backed by an established claim, or a composition of certified parts. A residual below a tolerance is none of these.

Every metric is read with the computed value first and the target second. Absolute error, absolute error of log weights and total variation satisfy the triangle inequality. Relative error does not: with target \(1\), an intermediate value \(100\) and a computed value \(101\) it is \(100\), against \(0.01 + 99\) through the intermediate value. Kullback-Leibler divergence does not: for Bernoulli laws with means \(0.1\), \(0.5\) and \(0.9\) it is \(1.758\) from the first to the third, against \(0.368 + 0.511\) through the second. Since the logarithm maps the nonnegative reals isomorphically onto the log weights, a relative error of probabilities is an absolute error of log weights.

The composition law

compose gives the attainment of an operation \(g : X_1 \times \dots \times X_n \to Y\) applied to results that each have an attainment. Write \(x_i\) for the targets, \(\hat x_i\) for the computed values, \(y = g(x_1, \dots, x_n)\), and \(\hat y = \hat g(\hat x_1, \dots, \hat x_n)\) for the computed result, where \(\hat g\) is the floating point implementation of \(g\). Let \(d\) be the metric of \(Y\) and \(d_i\) the metric of part \(i\).

Hypotheses.

  1. Lipschitz constants. For each argument with a constant \(L_i \ge 0\), and all points \(z, z'\) of a product region \(R\) that contains \((x_1, \dots, x_n)\) and \((\hat x_1, \dots, \hat x_n)\) and that differ only in coordinate \(i\), \(d(g(z), g(z')) \le L_i \, d_i(z_i, z'_i)\). This is Lipschitz continuity in each argument.
  2. Rounding of the operation. \(d(\hat y, g(\hat x_1, \dots, \hat x_n)) \le r\).
  3. Parts. \(d_i(\hat x_i, x_i) \le e_i + \rho_i\), where \(e_i\) is the bound of the part's guarantee (\(0\) when exact) and \(\rho_i\) its rounding bound. For a certified part this holds on every run; for a probabilistic part, outside an event \(F_i\) with \(P(F_i) \le \delta_i\).
  4. Triangle inequality. \(d(a, c) \le d(a, b) + d(b, c)\) on \(Y\).

Theorem. Under these hypotheses, outside \(F_1 \cup \dots \cup F_n\),

\[ d(\hat y, y) \;\le\; \sum_i L_i e_i \;+\; \Big( r + \sum_i L_i \rho_i \Big), \]

and \(P(F_1 \cup \dots \cup F_n) \le \sum_i \delta_i\).

Proof. Let \(h_0 = (\hat x_1, \dots, \hat x_n)\) and \(h_k = (x_1, \dots, x_k, \hat x_{k+1}, \dots, \hat x_n)\), so \(h_n = (x_1, \dots, x_n)\). Each coordinate of each \(h_k\) is a target or a computed value, so every \(h_k\) lies in the product region \(R\), and \(h_{k-1}\), \(h_k\) differ only in coordinate \(k\), where they hold \(\hat x_k\) and \(x_k\). Applying the triangle inequality \(n\) times along \(\hat y, g(h_0), g(h_1), \dots, g(h_n) = y\),

\[ d(\hat y, y) \le d(\hat y, g(h_0)) + \sum_{k=1}^{n} d(g(h_{k-1}), g(h_k)) \le r + \sum_{k=1}^{n} L_k \, d_k(\hat x_k, x_k) \]

by hypotheses 2 and 1. Outside \(\bigcup_i F_i\) every part satisfies hypothesis 3, and \(L_k \ge 0\), so the sum is at most \(\sum_k L_k (e_k + \rho_k)\), which rearranges to the bound. The probability of the union is at most the sum of the probabilities by the union bound, which needs no independence. QED

Corollary (the guarantee of a composite). The composite takes the weakest guarantee of its parts, in the order exact, certified, probabilistic, heuristic:

  1. every part exact: the composite is exact, with rounding \(r + \sum_i L_i \rho_i\) when every term is known, and unknown otherwise;
  2. every part exact or certified, each certified part with a constant in its own metric: certified with bound \(\sum_i L_i e_i\), and its certificate is the Composition of the terms, which can be checked again;
  3. some part probabilistic, the rest as in 2: probabilistic with bound \(\sum_i L_i e_i\) and failure probability \(\sum_i \delta_i\), when this is below one; at one or more the statement says nothing and the composite is heuristic;
  4. some part that is not exact without a constant in its own metric, some heuristic part with a constant above zero, or a metric of \(Y\) without the triangle inequality while some part is not exact: heuristic.

Case 4 is sharp. With \(g\) the identity, a heuristic part may be arbitrarily far from its target, so no finite bound holds; without the triangle inequality the step of the proof fails, as the two counterexamples above show. A heuristic part whose constant is zero does not move the result and is left out.

Local tolerances do not make a global bound. A run that stops because a residual fell below its tolerance has no certificate, so attained_guarantee makes it heuristic, and by case 4 so is every composite that depends on it. The residual can be small while the error is large: Kleene iteration of a cycle of weight \(0.999\), stopped when the log weight changes by less than \(10^{-3}\), returns \(6.2158\) after \(693\) iterates, while the exact log weight is \(\log 1000 = 6.9078\).

Derivatives of a composite. The derivative of a composite is the weakest of the derivatives of its parts and of the operation itself, component by component (below), with two differences from the meet. The unrolled loops of all parts are counted together, since each part unrolls its own loop. An estimate stays unbiased only when every estimated part is unbiased and enters an argument in which the operation is affine, because an expectation commutes with sums and deterministic multiples and not with other functions: for a Bernoulli draw \(X\) with mean \(p\), \(X\) is unbiased for \(p\), while \(E[X^2] = p\) differs from \(p^2\). Otherwise the bias is unknown. The composite is almost everywhere regular when every part and the operation are: these are computations whose primitives are analytic and whose decisions are sign tests of computed values, a class closed under composition, and the zero set of an analytic function that is not identically zero has measure zero. So the composite is at most as strong as each part.

Derivative semantics and reports

A DerivativeSemantics is a product of components, each ordered from strong to weak: whether a derivative exists, whether regular points have full measure, the tie rule of every selection, the hypotheses of implicit derivatives, the iteration counts of unrolled loops, the estimator of each random site, and the bias of the estimate. at_least compares them component by component, so it is a preorder with no derivative at the bottom, and meet is its greatest lower bound. Two tie rules have no meet: mixing them makes a result depend on bracketing, so there is one rule, FIRST_MAXIMIZER.

The forms of a derivative report are points of this order: exact at regular points, a selected branch at ties, implicit under conditions, unrolled, an estimator per site with its bias, and none with its reason. A DerivativeReport holds one semantics per output and input of a run, its summary is the meet of its entries, and an AccuracyReport requires the derivative of its attainment to be that summary. An estimator report is the estimator and bias components of the same record, so a derivative report of a handled program is an instance of these records, not a second kind.

Reports and failure

Three rules hold of every report that report_refusals admits:

  • a resource budget is never an error bound: no guarantee accepts a budget as its bound, and an exhausted run claims only the bound of a certificate it computed;
  • a residual is never a certificate;
  • exhaustion never returns a value labelled exact.

settle applies the failure policy: the value when the report meets the contract, ContractNotMet under REFUSE, and an Unestablished wrapper under RETURN_UNESTABLISHED. The wrapper is not a number, so nothing that expects a weight accepts it. No policy truncates silently, switches method, or returns zero.

Admissibility

admissibility returns every reason a query, its recursion, its contract and the available claims do not fit; report_refusals does the same for a report, and complexity_refusals for a complexity claim.

refusal refused combination
missing-claim a law the observable, the recursion or the executor needs has no claim
claim-not-established a needed law is only tested or assumed, and the guarantee is not heuristic
exact-without-finite-method an exact guarantee for a monotone polynomial or unrolled system
derivative-unavailable a derivative the recursion does not give
gradient-without-inputs a derivative with respect to nothing
inputs-without-gradient inputs to differentiate, and no derivative requested
observable-not-differentiable a derivative of support, a sample or the forest
selection-without-tie-rule a derivative of a best derivation without the tie rule it accepts
forest-not-retained a fold or the forest without the packed forest
infinite-derivations a guaranteed nonlinear fold of a system that can have infinitely many derivations
request-with-certificate a requested bound that carries a certificate
duplicate-control a control set twice
early-stop-labelled-exact a run stopped by its budget or a control, reported exact
certified-without-certificate an attained bound without its certificate
bound-below-certificate an attained bound below what its certificate shows
argument-not-established a bound argued from a claim that is only tested or assumed
certificate-metric an enclosure outside absolute errors, or a duality gap outside objective gaps
used-claim-not-established a guaranteed result from a run that used a claim that is not established
exact-for-inexact-recursion an exact result of a monotone polynomial or unrolled system
unmet-misreported unmet requirements that differ from the ones the contract and the attainment give
incomplete-claim a phase with neither a time and a space bound nor a declaration that it does not apply, or with both
undeclared-parameter a bound in a name the claim does not declare
lower-bound-mismatch an optimality proof whose lower bound is not the bound

Complexity claims and work

A ComplexityClaim states time and space bounds for construction, execution, differentiation and refitting in named parameters, in a stated ComputationModel. Each bound has a status: ProvedOptimal with the matching lower bound and its model, Conditional on a hypothesis, BestKnown, Unresolved as a research obligation, or Deficient with a better bound and a reviewed justification. A WorkReport counts the work of one phase in elements inside tensor operations, and a run exceeds its budget when the counts, added over phases, or the peaks, compared phase by phase, pass a limit.

contracts

Contract records: what a query asks for and what a run may claim.

A query names its observable, the laws it relies on, how recursion is solved, how accurate the answer must be, what the work costs, and what provenance is kept. Each of these is a record here, and every record crosses the QIEC wire codec.

Three rules hold by construction and are checked again by report_refusals:

  • a resource budget is never an error bound: budgets are counts of work, and no guarantee accepts one as its bound;
  • a residual is never a certificate: a run that stopped on a control claims a bound only through a certificate, and a certificate is an enclosure, a duality gap, an established argument, or a composition of certified parts;
  • exhaustion never returns a value labelled exact.

compose is the composition law of accuracy guarantees: the composite takes the weakest guarantee of its parts, and error bounds propagate through declared Lipschitz constants. Local tolerances alone give a heuristic composite. The proof is in the API page of this module.

ZERO module-attribute

ZERO = Rational(numerator=0)

The rational zero.

SPECTRAL_RADIUS_BELOW_ONE module-attribute

SPECTRAL_RADIUS_BELOW_ONE = Condition(name='spectral-radius-below-one', statement='the spectral radius of the Jacobian of the system at its least fixed point is below one, so the implicit derivative (I - DF)^-1 dF exists')

The hypothesis of the implicit derivative of a least fixed point.

NOT_DIFFERENTIATED module-attribute

NOT_DIFFERENTIATED = DerivativeSemantics.none('not differentiated')

The semantics of a run that computes no derivative.

UNLIMITED module-attribute

UNLIMITED = ResourceBudget()

A budget without limits.

ALGEBRA_OPERATIONS module-attribute

ALGEBRA_OPERATIONS = ComputationModel(name='algebra-operations', description='one unit per scalar operation of the weight algebra, counted inside tensor kernels')

Algebra operations at unit cost on scalars.

WORD_RAM_EXPECTED_HASHING module-attribute

WORD_RAM_EXPECTED_HASHING = ComputationModel(name='word-ram-expected-hashing', description='word RAM for indices, with hashing in expected constant time')

A word RAM with expected constant time hashing.

BOUND_FUNCTIONS module-attribute

BOUND_FUNCTIONS = frozenset({'log', 'min', 'max', 'sqrt', 'exp', 'poly', 'polylog', 'BM', 'omega'})

Function and constant names a bound may use besides its parameters.

BM(n) is the cost of a Boolean matrix product and omega the exponent of matrix multiplication.

TIME_FIELDS module-attribute

TIME_FIELDS: frozenset[WorkField] = frozenset({WorkField.SCALAR_SUMS, WorkField.SCALAR_PRODUCTS, WorkField.SCALAR_DIVISIONS, WorkField.STAR_PIVOTS, WorkField.EXACT_OPERATIONS, WorkField.KEY_COMPARISONS, WorkField.HASH_OPERATIONS})

The counters whose sum is the time of the algebra-operations model.

SPACE_FIELDS module-attribute

SPACE_FIELDS: Mapping[Phase, frozenset[WorkField]] = MappingProxyType({Phase.CONSTRUCTION: frozenset({WorkField.PEAK_LIVE_ELEMENTS}), Phase.EXECUTION: frozenset({WorkField.PEAK_LIVE_ELEMENTS}), Phase.DIFFERENTIATION: frozenset({WorkField.PEAK_LIVE_ELEMENTS, WorkField.ELEMENTS_SAVED_FOR_BACKWARD}), Phase.REFIT: frozenset({WorkField.PEAK_LIVE_ELEMENTS})})

The counters whose largest is the space of a phase in the model.

Bias

What is known about the expectation of a derivative estimate.

Metric

How the distance between a computed value and its target is measured.

Every metric is read with the computed value first and the target second.

Certificate

Evidence for a certified bound. A residual is not one of them.

Guarantee

What is promised about the distance between a result and its target.

Recursion

How a recursive system is solved, and what that solution is.

Retention

Which provenance a run keeps beside the autograd tape.

Observable

What a query observes of the detailed meaning of a judgment.

OptimalityStatus

How a bound compares with what is known to be possible.

StopReason

Why a run stopped.

PresentationId didactic-model

PresentationId(*, digest: str)

Bases: StableId

Stable identity of a rule presentation.

InterpretationId didactic-model

InterpretationId(*, digest: str)

Bases: StableId

Stable identity of an interpretation of a rule presentation.

OccurrenceId didactic-model

OccurrenceId(*, digest: str)

Bases: StableId

Stable identity of one occurrence of an axiom or a weight.

ParameterId didactic-model

ParameterId(*, digest: str)

Bases: StableId

Stable identity of a trainable parameter.

Rational didactic-model

Rational(*, numerator: int, denominator: int = 1)

Bases: QiecModel

An exact nonnegative or signed rational number in lowest terms.

Bounds are exact so that adding them, as the composition law does, never rounds a bound down.

PARAMETER DESCRIPTION
numerator

The numerator.

TYPE: int

denominator

The denominator, positive and coprime to the numerator.

TYPE: int DEFAULT: 1

RAISES DESCRIPTION
ValidationError

If the denominator is not positive or the fraction is not in lowest terms.

fraction property

fraction: Fraction

The number as a fractions.Fraction.

RETURNS DESCRIPTION
Fraction

The same number.

of classmethod

of(value: Fraction | int | float) -> Rational

Build the rational equal to a number.

PARAMETER DESCRIPTION
value

The number. A float converts exactly, digit for digit of its binary value.

TYPE: Fraction or int or float

RETURNS DESCRIPTION
Rational

The same number in lowest terms.

RAISES DESCRIPTION
ValueError

If the value is a boolean or a float that is not finite.

Source code in src/quivers/qiec/contracts.py
@classmethod
def of(cls, value: Fraction | int | float) -> Rational:
    """Build the rational equal to a number.

    Parameters
    ----------
    value : Fraction or int or float
        The number. A float converts exactly, digit for digit of its
        binary value.

    Returns
    -------
    Rational
        The same number in lowest terms.

    Raises
    ------
    ValueError
        If the value is a boolean or a float that is not finite.
    """
    if isinstance(value, bool):
        raise ValueError("a boolean is not a number here")
    if isinstance(value, float) and not isfinite(value):
        raise ValueError("a bound is finite; an infinite bound is no bound")
    exact = Fraction(value)
    return cls(numerator=exact.numerator, denominator=exact.denominator)

Condition didactic-model

Condition(*, name: str, statement: str)

Bases: QiecModel

A hypothesis under which a result holds.

PARAMETER DESCRIPTION
name

A short name, unique among conditions.

TYPE: str

statement

The hypothesis.

TYPE: str

Unbiased didactic-model

Unbiased(*, tag: Literal['unbiased'] = 'unbiased')

Bases: QiecModel

An estimate whose expectation is the quantity estimated.

PARAMETER DESCRIPTION
tag

Always "unbiased".

TYPE: str DEFAULT: 'unbiased'

BiasBound didactic-model

BiasBound(*, bound: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['bias-bound'] = 'bias-bound')

Bases: QiecModel

An estimate whose bias is at most a declared positive bound.

PARAMETER DESCRIPTION
bound

The bound on the norm of the bias, positive.

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

tag

Always "bias-bound".

TYPE: str DEFAULT: 'bias-bound'

BiasUnknown didactic-model

BiasUnknown(*, tag: Literal['bias-unknown'] = 'bias-unknown')

Bases: QiecModel

An estimate with a bias of unknown size.

PARAMETER DESCRIPTION
tag

Always "bias-unknown".

TYPE: str DEFAULT: 'bias-unknown'

SiteEstimator didactic-model

SiteEstimator(*, site: SiteId = field(opaque=True, extras=OPAQUE_BY_VALUE), estimator: str)

Bases: QiecModel

The estimator that handles one random site under differentiation.

PARAMETER DESCRIPTION
site

The site.

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

estimator

Its estimator, such as "enumerate", "score", "measure" or "reparam", or a declared estimator such as "straight-through".

TYPE: str

DerivativeSemantics didactic-model

DerivativeSemantics(*, missing: tuple[str, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), almost_everywhere: bool = False, tie_rule: TieRule | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), implicit_conditions: tuple[Condition, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), unrolled: tuple[int, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), estimators: tuple[SiteEstimator, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), bias: Bias = field(default=Unbiased(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

What a derivative is the derivative of, and how it was obtained.

The record is a product of independent components, each ordered from strong to weak, and one semantics is at least as strong as another when it is in every component (at_least). The forms of a derivative report are its points:

  • exact at regular points (exact), almost everywhere when every primitive is analytic and every decision is a sign test;
  • a selected branch at ties (selected_branch), by one tie rule;
  • implicit (implicit), under stated conditions;
  • unrolled (unrolled): the derivative of the first k iterates and of nothing else;
  • an estimator (estimated) per random site, with its bias;
  • none (none), with the reason.

A composite holds several at once, and kind names its weakest.

PARAMETER DESCRIPTION
missing

Reasons why there is no derivative. When any is given, every other component is at its strongest value.

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

almost_everywhere

Whether the regular points have full measure.

TYPE: bool DEFAULT: False

tie_rule

The rule of every selection in the computation, or None when it makes no selection.

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

implicit_conditions

Hypotheses of implicit derivatives, sorted and without repeats.

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

unrolled

Iteration counts of the unrolled loops the derivative passes through, sorted, one entry per loop.

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

estimators

The estimator of each random site, sorted, one per site.

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

bias

What is known about the expectation of the estimate.

TYPE: Bias DEFAULT: field(default=Unbiased(), opaque=True, extras=OPAQUE_BY_VALUE)

RAISES DESCRIPTION
ValidationError

If a missing derivative carries other components, a loop has fewer than one iteration, a site has two estimators, or a bias is declared without an estimator.

kind property

kind: str

The weakest form the semantics holds.

RETURNS DESCRIPTION
str

"none", "unrolled", "estimator", "implicit", "selected-branch" or "exact-at-regular-points", the first that applies.

exact classmethod

exact(*, almost_everywhere: bool = False) -> DerivativeSemantics

The exact derivative at regular points.

PARAMETER DESCRIPTION
almost_everywhere

Whether the regular points have full measure.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DerivativeSemantics

The strongest semantics.

Source code in src/quivers/qiec/contracts.py
@classmethod
def exact(cls, *, almost_everywhere: bool = False) -> DerivativeSemantics:
    """The exact derivative at regular points.

    Parameters
    ----------
    almost_everywhere : bool
        Whether the regular points have full measure.

    Returns
    -------
    DerivativeSemantics
        The strongest semantics.
    """
    return cls(almost_everywhere=almost_everywhere)

selected_branch classmethod

selected_branch(rule: TieRule, *, almost_everywhere: bool = False) -> DerivativeSemantics

The exact derivative at regular points, and a rule's element at ties.

PARAMETER DESCRIPTION
rule

The tie rule of every selection.

TYPE: TieRule

almost_everywhere

Whether the regular points have full measure.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DerivativeSemantics

The semantics.

Source code in src/quivers/qiec/contracts.py
@classmethod
def selected_branch(
    cls, rule: TieRule, *, almost_everywhere: bool = False
) -> DerivativeSemantics:
    """The exact derivative at regular points, and a rule's element at ties.

    Parameters
    ----------
    rule : TieRule
        The tie rule of every selection.
    almost_everywhere : bool
        Whether the regular points have full measure.

    Returns
    -------
    DerivativeSemantics
        The semantics.
    """
    return cls(tie_rule=rule, almost_everywhere=almost_everywhere)

implicit classmethod

implicit(*conditions: Condition) -> DerivativeSemantics

The implicit derivative under hypotheses.

PARAMETER DESCRIPTION
conditions

The hypotheses.

TYPE: Condition DEFAULT: ()

RETURNS DESCRIPTION
DerivativeSemantics

The semantics.

Source code in src/quivers/qiec/contracts.py
@classmethod
def implicit(cls, *conditions: Condition) -> DerivativeSemantics:
    """The implicit derivative under hypotheses.

    Parameters
    ----------
    conditions : Condition
        The hypotheses.

    Returns
    -------
    DerivativeSemantics
        The semantics.
    """
    return cls(implicit_conditions=conditions)

unrolled_iterations classmethod

unrolled_iterations(*iterations: int) -> DerivativeSemantics

The derivative of unrolled loops and of nothing else.

PARAMETER DESCRIPTION
iterations

The iteration count of each loop.

TYPE: int DEFAULT: ()

RETURNS DESCRIPTION
DerivativeSemantics

The semantics.

Source code in src/quivers/qiec/contracts.py
@classmethod
def unrolled_iterations(cls, *iterations: int) -> DerivativeSemantics:
    """The derivative of unrolled loops and of nothing else.

    Parameters
    ----------
    iterations : int
        The iteration count of each loop.

    Returns
    -------
    DerivativeSemantics
        The semantics.
    """
    return cls(unrolled=iterations)

estimated classmethod

estimated(*estimators: SiteEstimator, bias: Bias = Unbiased()) -> DerivativeSemantics

An estimate of the derivative from estimators at random sites.

PARAMETER DESCRIPTION
estimators

The estimator of each site.

TYPE: SiteEstimator DEFAULT: ()

bias

What is known about the expectation of the estimate.

TYPE: Bias DEFAULT: Unbiased()

RETURNS DESCRIPTION
DerivativeSemantics

The semantics.

Source code in src/quivers/qiec/contracts.py
@classmethod
def estimated(
    cls, *estimators: SiteEstimator, bias: Bias = Unbiased()
) -> DerivativeSemantics:
    """An estimate of the derivative from estimators at random sites.

    Parameters
    ----------
    estimators : SiteEstimator
        The estimator of each site.
    bias : Bias
        What is known about the expectation of the estimate.

    Returns
    -------
    DerivativeSemantics
        The semantics.
    """
    return cls(estimators=estimators, bias=bias)

none classmethod

none(*reasons: str) -> DerivativeSemantics

No derivative.

PARAMETER DESCRIPTION
reasons

Why there is none.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
DerivativeSemantics

The weakest semantics.

RAISES DESCRIPTION
ValueError

If no reason is given.

Source code in src/quivers/qiec/contracts.py
@classmethod
def none(cls, *reasons: str) -> DerivativeSemantics:
    """No derivative.

    Parameters
    ----------
    reasons : str
        Why there is none.

    Returns
    -------
    DerivativeSemantics
        The weakest semantics.

    Raises
    ------
    ValueError
        If no reason is given.
    """
    if not reasons:
        raise ValueError("a missing derivative names its reason")
    return cls(missing=reasons)

at_least

at_least(request: DerivativeSemantics) -> bool

Whether this semantics is at least as strong as a request.

PARAMETER DESCRIPTION
request

The weakest semantics that is acceptable.

TYPE: DerivativeSemantics

RETURNS DESCRIPTION
bool

True when the request asks for no derivative, or when in every component this one is at least as strong: no missing derivative, regular points of full measure if asked, a tie rule only if the request has the same one, and conditions, unrolled loops and estimators that the request admits, with a bias no larger than the request's.

Source code in src/quivers/qiec/contracts.py
def at_least(self, request: DerivativeSemantics) -> bool:
    """Whether this semantics is at least as strong as a request.

    Parameters
    ----------
    request : DerivativeSemantics
        The weakest semantics that is acceptable.

    Returns
    -------
    bool
        True when the request asks for no derivative, or when in
        every component this one is at least as strong: no missing
        derivative, regular points of full measure if asked, a tie
        rule only if the request has the same one, and conditions,
        unrolled loops and estimators that the request admits, with a
        bias no larger than the request's.
    """
    if request.missing:
        return True
    if self.missing:
        return False
    if request.almost_everywhere and not self.almost_everywhere:
        return False
    if self.tie_rule is not None and self.tie_rule != request.tie_rule:
        return False
    if not set(self.implicit_conditions) <= set(request.implicit_conditions):
        return False
    if Counter(self.unrolled) - Counter(request.unrolled):
        return False
    if not set(self.estimators) <= set(request.estimators):
        return False
    return _bias_rank(self.bias) <= _bias_rank(request.bias)

meet

The strongest semantics that both this one and another reach.

PARAMETER DESCRIPTION
other

The other semantics.

TYPE: DerivativeSemantics

RETURNS DESCRIPTION
DerivativeSemantics

The componentwise weakest: the reasons of both when either has none, regular points of full measure only if both have them, the tie rule of either, the union of conditions and of estimators, the larger count of each unrolled loop length, and the larger bias.

RAISES DESCRIPTION
ValueError

If the two use different tie rules, or estimate one site by two estimators. Neither has a meet: mixing tie rules makes a result depend on bracketing.

Source code in src/quivers/qiec/contracts.py
def meet(self, other: DerivativeSemantics) -> DerivativeSemantics:
    """The strongest semantics that both this one and another reach.

    Parameters
    ----------
    other : DerivativeSemantics
        The other semantics.

    Returns
    -------
    DerivativeSemantics
        The componentwise weakest: the reasons of both when either
        has none, regular points of full measure only if both have
        them, the tie rule of either, the union of conditions and of
        estimators, the larger count of each unrolled loop length,
        and the larger bias.

    Raises
    ------
    ValueError
        If the two use different tie rules, or estimate one site by
        two estimators. Neither has a meet: mixing tie rules makes a
        result depend on bracketing.
    """
    if self.missing or other.missing:
        return DerivativeSemantics.none(*self.missing, *other.missing)
    unrolled = Counter(self.unrolled) | Counter(other.unrolled)
    return DerivativeSemantics(
        almost_everywhere=self.almost_everywhere and other.almost_everywhere,
        tie_rule=_one_tie_rule(self.tie_rule, other.tie_rule),
        implicit_conditions=(*self.implicit_conditions, *other.implicit_conditions),
        unrolled=tuple(unrolled.elements()),
        estimators=_one_estimator_per_site(self.estimators, other.estimators),
        bias=max(self.bias, other.bias, key=_bias_rank),
    )

DerivativeEntry didactic-model

DerivativeEntry(*, output: str, wrt: ParameterId | OccurrenceId = field(opaque=True, extras=OPAQUE_BY_VALUE), semantics: DerivativeSemantics = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The derivative semantics of one output with respect to one input.

PARAMETER DESCRIPTION
output

The output.

TYPE: str

wrt

The parameter or the occurrence differentiated.

TYPE: ParameterId or OccurrenceId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

semantics

What the derivative is.

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

DerivativeReport didactic-model

DerivativeReport(*, entries: tuple[DerivativeEntry, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The derivative semantics of every output and input of a run.

PARAMETER DESCRIPTION
entries

One entry per output and input, without repeats.

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

RAISES DESCRIPTION
ValidationError

If an output and input pair has two entries.

summary property

The strongest semantics every entry reaches.

RETURNS DESCRIPTION
DerivativeSemantics

The meet of the entries, or NOT_DIFFERENTIATED when there is none.

AbsoluteError didactic-model

AbsoluteError(*, tag: Literal['absolute'] = 'absolute')

Bases: QiecModel

The distance |computed - target|.

PARAMETER DESCRIPTION
tag

Always "absolute".

TYPE: str DEFAULT: 'absolute'

triangle_inequality property

triangle_inequality: bool

Whether the triangle inequality holds.

RETURNS DESCRIPTION
bool

True: it is a metric.

AbsoluteLogError didactic-model

AbsoluteLogError(*, tag: Literal['absolute-log'] = 'absolute-log')

Bases: QiecModel

The distance |log computed - log target| on positive weights.

Since the logarithm is a semiring isomorphism from the nonnegative reals onto the log weights, a relative error of probabilities is an absolute error of log weights.

PARAMETER DESCRIPTION
tag

Always "absolute-log".

TYPE: str DEFAULT: 'absolute-log'

triangle_inequality property

triangle_inequality: bool

Whether the triangle inequality holds.

RETURNS DESCRIPTION
bool

True: it is a metric.

RelativeError didactic-model

RelativeError(*, tag: Literal['relative'] = 'relative')

Bases: QiecModel

The divergence |computed - target| / |target|.

It fails the triangle inequality: with target 1, a midpoint of 100 and a computed value of 101, it is 100 against 0.01 plus 99.

PARAMETER DESCRIPTION
tag

Always "relative".

TYPE: str DEFAULT: 'relative'

triangle_inequality property

triangle_inequality: bool

Whether the triangle inequality holds.

RETURNS DESCRIPTION
bool

False.

TotalVariation didactic-model

TotalVariation(*, tag: Literal['total-variation'] = 'total-variation')

Bases: QiecModel

The total variation distance between two distributions.

PARAMETER DESCRIPTION
tag

Always "total-variation".

TYPE: str DEFAULT: 'total-variation'

triangle_inequality property

triangle_inequality: bool

Whether the triangle inequality holds.

RETURNS DESCRIPTION
bool

True: it is a metric.

KLDivergence didactic-model

KLDivergence(*, direction: Literal['target-to-computed', 'computed-to-target'], tag: Literal['kl'] = 'kl')

Bases: QiecModel

The Kullback-Leibler divergence in a stated direction.

It fails the triangle inequality: for Bernoulli laws with means 0.1, 0.5 and 0.9 it is 1.758 from the first to the third against 0.368 plus 0.511 through the second.

PARAMETER DESCRIPTION
direction

"target-to-computed" for D(target || computed) or "computed-to-target" for D(computed || target).

TYPE: str

tag

Always "kl".

TYPE: str DEFAULT: 'kl'

triangle_inequality property

triangle_inequality: bool

Whether the triangle inequality holds.

RETURNS DESCRIPTION
bool

False.

ObjectiveGap didactic-model

ObjectiveGap(*, tag: Literal['objective-gap'] = 'objective-gap')

Bases: QiecModel

The gap between an objective at the computed point and its optimum.

PARAMETER DESCRIPTION
tag

Always "objective-gap".

TYPE: str DEFAULT: 'objective-gap'

triangle_inequality property

triangle_inequality: bool

Whether the triangle inequality holds.

RETURNS DESCRIPTION
bool

False: it compares objective values, not the points.

Enclosure didactic-model

Enclosure(*, lower: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), upper: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[str, ...] = (), tag: Literal['enclosure'] = 'enclosure')

Bases: QiecModel

An interval that holds both the target and the computed value.

The endpoints come from outward rounded interval arithmetic, such as a lower iterate and a pre-fixed point of a monotone system. The bound it certifies is the width.

PARAMETER DESCRIPTION
lower

The lower endpoint.

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

upper

The upper endpoint, at least the lower one.

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

conditions

What the enclosure rests on.

TYPE: tuple of str DEFAULT: ()

tag

Always "enclosure".

TYPE: str DEFAULT: 'enclosure'

bound property

bound: Fraction

The bound the enclosure certifies.

RETURNS DESCRIPTION
Fraction

The width of the interval.

DualityGap didactic-model

DualityGap(*, primal: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), dual: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[str, ...] = (), tag: Literal['duality-gap'] = 'duality-gap')

Bases: QiecModel

A primal value and a dual bound of an optimization.

The optimum lies between them, so the gap bounds how far the primal value is from it.

PARAMETER DESCRIPTION
primal

The objective of a feasible point.

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

dual

A bound on the optimum, on the other side.

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

conditions

What the dual bound rests on, such as exact local solves.

TYPE: tuple of str DEFAULT: ()

tag

Always "duality-gap".

TYPE: str DEFAULT: 'duality-gap'

bound property

bound: Fraction

The bound the gap certifies.

RETURNS DESCRIPTION
Fraction

|dual - primal|.

Argument didactic-model

Argument(*, value: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), claim: LawClaim = field(opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[str, ...] = (), tag: Literal['argument'] = 'argument')

Bases: QiecModel

A bound that an established claim proves.

PARAMETER DESCRIPTION
value

The bound, at least zero.

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

claim

The theorem that gives the bound, such as an a posteriori bound of a contraction with a proved rate. It must be established.

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

conditions

The hypotheses of the theorem that the run checked.

TYPE: tuple of str DEFAULT: ()

tag

Always "argument".

TYPE: str DEFAULT: 'argument'

bound property

bound: Fraction

The bound the argument certifies.

RETURNS DESCRIPTION
Fraction

The stated bound.

ComposedTerm didactic-model

ComposedTerm(*, lipschitz: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), bound: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One part of a composition: its bound and its Lipschitz constant.

PARAMETER DESCRIPTION
lipschitz

The constant of the operation in the part's argument.

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

bound

The part's bound.

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

Composition didactic-model

Composition(*, operation: str, terms: tuple[ComposedTerm, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[str, ...] = (), tag: Literal['composition'] = 'composition')

Bases: QiecModel

A bound obtained by the composition law from certified parts.

PARAMETER DESCRIPTION
operation

The operation that combines the parts.

TYPE: str

terms

The parts that are not exact.

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

conditions

The conditions of the parts and of the constants.

TYPE: tuple of str DEFAULT: ()

tag

Always "composition".

TYPE: str DEFAULT: 'composition'

bound property

bound: Fraction

The bound the composition certifies.

RETURNS DESCRIPTION
Fraction

The sum of each constant times its part's bound.

Exact didactic-model

Exact(*, tag: Literal['exact'] = 'exact')

Bases: QiecModel

The mathematical value, up to the rounding stated in Numerics.

PARAMETER DESCRIPTION
tag

Always "exact".

TYPE: str DEFAULT: 'exact'

Certified didactic-model

Certified(*, bound: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[str, ...] = (), certificate: Certificate | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['certified'] = 'certified')

Bases: QiecModel

A bound that holds on every run, up to the stated rounding.

In a contract it is the requested bound and carries no certificate. In a report it is the attained bound and must carry the certificate that shows it.

PARAMETER DESCRIPTION
bound

The bound on the distance to the target, at least zero.

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

conditions

The hypotheses under which it holds.

TYPE: tuple of str DEFAULT: ()

certificate

The evidence, in a report.

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

tag

Always "certified".

TYPE: str DEFAULT: 'certified'

Probabilistic didactic-model

Probabilistic(*, epsilon: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), delta: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), assumptions: tuple[str, ...] = (), tag: Literal['probabilistic'] = 'probabilistic')

Bases: QiecModel

A bound that fails with probability at most delta.

PARAMETER DESCRIPTION
epsilon

The bound, at least zero.

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

delta

The probability of failure, strictly between zero and one.

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

assumptions

What the probability rests on.

TYPE: tuple of str DEFAULT: ()

tag

Always "probabilistic".

TYPE: str DEFAULT: 'probabilistic'

Heuristic didactic-model

Heuristic(*, reason: str, tag: Literal['heuristic'] = 'heuristic')

Bases: QiecModel

No guarantee.

PARAMETER DESCRIPTION
reason

Why there is none.

TYPE: str

tag

Always "heuristic".

TYPE: str DEFAULT: 'heuristic'

Numerics didactic-model

Numerics(*, dtype: Literal['bool', 'int64', 'float16', 'bfloat16', 'float32', 'float64'], domain: Literal['linear', 'log'] = 'linear', reduction: Literal['plain', 'compensated'] = 'plain', rounding: Rational | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Precision of a computation.

PARAMETER DESCRIPTION
dtype

The element type.

TYPE: str

domain

"linear" or "log" weights.

TYPE: str DEFAULT: 'linear'

reduction

"plain" or "compensated" summation.

TYPE: str DEFAULT: 'plain'

rounding

A bound on the rounding error in the target's metric, from the operation count and the condition number, or None when no bound is known. In a contract it is the largest acceptable.

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

Target didactic-model

Target(*, quantity: str, metric: Metric = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The mathematical quantity a result approximates, and its metric.

PARAMETER DESCRIPTION
quantity

The quantity, such as the observable of the query or the least fixed point of its system.

TYPE: str

metric

How distance to it is measured.

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

Control didactic-model

Control(*, name: str, value: Rational | str = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A method parameter. It is recorded and never read as a guarantee.

PARAMETER DESCRIPTION
name

Its name, such as "beam", "damping" or "tolerance".

TYPE: str

value

Its value.

TYPE: Rational or str DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

ResourceBudget didactic-model

ResourceBudget(*, iterations: int | None = None, scalar_work: int | None = None, states: int | None = None, elements: int | None = None, bytes: int | None = None, seconds: Rational | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Limits on the work of a run. A budget is never an error bound.

Each limit is None when there is none.

PARAMETER DESCRIPTION
iterations

Iterations of a solver.

TYPE: int or None DEFAULT: None

scalar_work

Scalar sums, products and divisions.

TYPE: int or None DEFAULT: None

states

Product states created.

TYPE: int or None DEFAULT: None

elements

Elements live at once.

TYPE: int or None DEFAULT: None

bytes

Bytes live at once.

TYPE: int or None DEFAULT: None

seconds

Wall time.

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

FailurePolicy

Bases: str, Enum

What a run does when it cannot meet its contract.

Neither policy truncates silently, switches method, or returns zero.

AccuracyContract didactic-model

AccuracyContract(*, numerics: Numerics = field(opaque=True, extras=OPAQUE_BY_VALUE), target: Target = field(opaque=True, extras=OPAQUE_BY_VALUE), guarantee: Guarantee = field(default=Exact(), opaque=True, extras=OPAQUE_BY_VALUE), controls: tuple[Control, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), budget: ResourceBudget = field(default=UNLIMITED, opaque=True, extras=OPAQUE_BY_VALUE), on_failure: FailurePolicy = field(default=REFUSE, opaque=True, extras=OPAQUE_BY_VALUE), gradient: DerivativeSemantics = field(default=NOT_DIFFERENTIATED, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

How accurate a result must be, and what happens when it is not.

The fields are separate on purpose: a method parameter is not a guarantee, a budget is not an error bound, and the derivative has its own semantics.

PARAMETER DESCRIPTION
numerics

Precision.

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

target

The quantity and its metric.

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

guarantee

The weakest acceptable guarantee.

TYPE: Guarantee DEFAULT: field(default=Exact(), opaque=True, extras=OPAQUE_BY_VALUE)

controls

Method parameters.

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

budget

Limits on work.

TYPE: ResourceBudget DEFAULT: field(default=UNLIMITED, opaque=True, extras=OPAQUE_BY_VALUE)

on_failure

Refuse, or return the value wrapped as unestablished.

TYPE: FailurePolicy DEFAULT: field(default=REFUSE, opaque=True, extras=OPAQUE_BY_VALUE)

gradient

The weakest acceptable derivative semantics, or NOT_DIFFERENTIATED.

TYPE: DerivativeSemantics DEFAULT: field(default=NOT_DIFFERENTIATED, opaque=True, extras=OPAQUE_BY_VALUE)

Acyclic didactic-model

Acyclic(*, tag: Literal['acyclic'] = 'acyclic')

Bases: QiecModel

The derived hypergraph has no cycle, found by parent counts.

The solution is unique, and one relaxation per hyperedge computes it.

PARAMETER DESCRIPTION
tag

Always "acyclic".

TYPE: str DEFAULT: 'acyclic'

finite_method property

finite_method: bool

Whether a finite procedure computes the exact value.

RETURNS DESCRIPTION
bool

True.

finite_derivations property

finite_derivations: bool

Whether every judgment has finitely many derivations.

RETURNS DESCRIPTION
bool

True.

laws

laws() -> tuple[Law, ...]

The laws the solution needs beyond the observable's.

RETURNS DESCRIPTION
tuple of Law

None.

Source code in src/quivers/qiec/contracts.py
def laws(self) -> tuple[Law, ...]:
    """The laws the solution needs beyond the observable's.

    Returns
    -------
    tuple of Law
        None.
    """
    return ()

admits

admits(gradient: DerivativeSemantics) -> bool

Whether a requested derivative is available.

PARAMETER DESCRIPTION
gradient

The request.

TYPE: DerivativeSemantics

RETURNS DESCRIPTION
bool

True: reverse accumulation of the computation is exact.

Source code in src/quivers/qiec/contracts.py
def admits(self, gradient: DerivativeSemantics) -> bool:
    """Whether a requested derivative is available.

    Parameters
    ----------
    gradient : DerivativeSemantics
        The request.

    Returns
    -------
    bool
        True: reverse accumulation of the computation is exact.
    """
    return True

LinearCyclic didactic-model

LinearCyclic(*, tag: Literal['linear-cyclic'] = 'linear-cyclic')

Bases: QiecModel

Each strongly connected component has at most one premise inside it.

The least solution is A* b in an algebra with a star.

PARAMETER DESCRIPTION
tag

Always "linear-cyclic".

TYPE: str DEFAULT: 'linear-cyclic'

finite_method property

finite_method: bool

Whether a finite procedure computes the exact value.

RETURNS DESCRIPTION
bool

True: elimination computes the star.

finite_derivations property

finite_derivations: bool

Whether every judgment has finitely many derivations.

RETURNS DESCRIPTION
bool

False.

laws

laws() -> tuple[Law, ...]

The laws the solution needs beyond the observable's.

RETURNS DESCRIPTION
tuple of Law

The star law.

Source code in src/quivers/qiec/contracts.py
def laws(self) -> tuple[Law, ...]:
    """The laws the solution needs beyond the observable's.

    Returns
    -------
    tuple of Law
        The star law.
    """
    return (STAR_LEAST_SOLUTION,)

admits

admits(gradient: DerivativeSemantics) -> bool

Whether a requested derivative is available.

PARAMETER DESCRIPTION
gradient

The request.

TYPE: DerivativeSemantics

RETURNS DESCRIPTION
bool

True: the derivative of A* is A* dA A* on the open domain of convergence.

Source code in src/quivers/qiec/contracts.py
def admits(self, gradient: DerivativeSemantics) -> bool:
    """Whether a requested derivative is available.

    Parameters
    ----------
    gradient : DerivativeSemantics
        The request.

    Returns
    -------
    bool
        True: the derivative of ``A*`` is ``A* dA A*`` on the open
        domain of convergence.
    """
    return True

MonotonePolynomial didactic-model

MonotonePolynomial(*, tag: Literal['monotone-polynomial'] = 'monotone-polynomial')

Bases: QiecModel

A nonnegative polynomial system x = f(x) with a least fixed point.

Kleene and Newton iterates increase to the least fixed point, and a pre-fixed point bounds it from above. No finite procedure computes it exactly in general, so the result is at best certified.

PARAMETER DESCRIPTION
tag

Always "monotone-polynomial".

TYPE: str DEFAULT: 'monotone-polynomial'

finite_method property

finite_method: bool

Whether a finite procedure computes the exact value.

RETURNS DESCRIPTION
bool

False.

finite_derivations property

finite_derivations: bool

Whether every judgment has finitely many derivations.

RETURNS DESCRIPTION
bool

False.

laws

laws() -> tuple[Law, ...]

The laws the solution needs beyond the observable's.

RETURNS DESCRIPTION
tuple of Law

None of their own: the least fixed point lies in the omega-continuous completion of the weights, and the executor that solves the system states the laws it uses, an embedding in the nonnegative reals for certified Newton or an idempotent sum with a star for exact Newton.

Source code in src/quivers/qiec/contracts.py
def laws(self) -> tuple[Law, ...]:
    """The laws the solution needs beyond the observable's.

    Returns
    -------
    tuple of Law
        None of their own: the least fixed point lies in the
        omega-continuous completion of the weights, and the executor
        that solves the system states the laws it uses, an embedding in
        the nonnegative reals for certified Newton or an idempotent sum
        with a star for exact Newton.
    """
    return ()

admits

admits(gradient: DerivativeSemantics) -> bool

Whether a requested derivative is available.

PARAMETER DESCRIPTION
gradient

The request.

TYPE: DerivativeSemantics

RETURNS DESCRIPTION
bool

True when the request asks for no derivative, admits the implicit derivative under its spectral condition, or admits an unrolled one.

Source code in src/quivers/qiec/contracts.py
def admits(self, gradient: DerivativeSemantics) -> bool:
    """Whether a requested derivative is available.

    Parameters
    ----------
    gradient : DerivativeSemantics
        The request.

    Returns
    -------
    bool
        True when the request asks for no derivative, admits the
        implicit derivative under its spectral condition, or admits
        an unrolled one.
    """
    return (
        bool(gradient.missing)
        or SPECTRAL_RADIUS_BELOW_ONE in gradient.implicit_conditions
        or bool(gradient.unrolled)
    )

Bounded didactic-model

Bounded(*, measure: Literal['constructor-depth', 'length', 'height'], limit: int, tag: Literal['bounded'] = 'bounded')

Bases: QiecModel

The model restricts its derivations by a bound that is part of it.

A bound on constructor depth, length or height changes the model and its name; an execution budget does not.

PARAMETER DESCRIPTION
measure

"constructor-depth", "length" or "height".

TYPE: str

limit

The bound, at least zero.

TYPE: int

tag

Always "bounded".

TYPE: str DEFAULT: 'bounded'

finite_method property

finite_method: bool

Whether a finite procedure computes the exact value.

RETURNS DESCRIPTION
bool

True.

finite_derivations property

finite_derivations: bool

Whether every judgment has finitely many derivations.

RETURNS DESCRIPTION
bool

True.

laws

laws() -> tuple[Law, ...]

The laws the solution needs beyond the observable's.

RETURNS DESCRIPTION
tuple of Law

None.

Source code in src/quivers/qiec/contracts.py
def laws(self) -> tuple[Law, ...]:
    """The laws the solution needs beyond the observable's.

    Returns
    -------
    tuple of Law
        None.
    """
    return ()

admits

admits(gradient: DerivativeSemantics) -> bool

Whether a requested derivative is available.

PARAMETER DESCRIPTION
gradient

The request.

TYPE: DerivativeSemantics

RETURNS DESCRIPTION
bool

True: the bounded model is finite and acyclic.

Source code in src/quivers/qiec/contracts.py
def admits(self, gradient: DerivativeSemantics) -> bool:
    """Whether a requested derivative is available.

    Parameters
    ----------
    gradient : DerivativeSemantics
        The request.

    Returns
    -------
    bool
        True: the bounded model is finite and acyclic.
    """
    return True

Unrolled didactic-model

Unrolled(*, iterations: int, tag: Literal['unrolled'] = 'unrolled')

Bases: QiecModel

The first iterations iterates of a recursive system.

In an ordered algebra with increasing iterates they bound the solution from below. They are not the solution, and their derivative is the derivative of the iterates and of nothing else.

PARAMETER DESCRIPTION
iterations

How many iterates, at least one.

TYPE: int

tag

Always "unrolled".

TYPE: str DEFAULT: 'unrolled'

finite_method property

finite_method: bool

Whether a finite procedure computes the exact value.

RETURNS DESCRIPTION
bool

False: the iterates are not the solution.

finite_derivations property

finite_derivations: bool

Whether every judgment has finitely many derivations.

RETURNS DESCRIPTION
bool

False.

laws

laws() -> tuple[Law, ...]

The laws the solution needs beyond the observable's.

RETURNS DESCRIPTION
tuple of Law

None.

Source code in src/quivers/qiec/contracts.py
def laws(self) -> tuple[Law, ...]:
    """The laws the solution needs beyond the observable's.

    Returns
    -------
    tuple of Law
        None.
    """
    return ()

admits

admits(gradient: DerivativeSemantics) -> bool

Whether a requested derivative is available.

PARAMETER DESCRIPTION
gradient

The request.

TYPE: DerivativeSemantics

RETURNS DESCRIPTION
bool

True when the request asks for no derivative or admits a loop unrolled this many times.

Source code in src/quivers/qiec/contracts.py
def admits(self, gradient: DerivativeSemantics) -> bool:
    """Whether a requested derivative is available.

    Parameters
    ----------
    gradient : DerivativeSemantics
        The request.

    Returns
    -------
    bool
        True when the request asks for no derivative or admits a loop
        unrolled this many times.
    """
    return bool(gradient.missing) or self.iterations in gradient.unrolled

NoRetention didactic-model

NoRetention(*, tag: Literal['none'] = 'none')

Bases: QiecModel

Keep no provenance beyond the values.

PARAMETER DESCRIPTION
tag

Always "none".

TYPE: str DEFAULT: 'none'

keeps_forest property

keeps_forest: bool

Whether the packed forest is kept.

RETURNS DESCRIPTION
bool

False.

ParentCounts didactic-model

ParentCounts(*, tag: Literal['parent-counts'] = 'parent-counts')

Bases: QiecModel

Keep a count of pending parents per item, and no edges.

PARAMETER DESCRIPTION
tag

Always "parent-counts".

TYPE: str DEFAULT: 'parent-counts'

keeps_forest property

keeps_forest: bool

Whether the packed forest is kept.

RETURNS DESCRIPTION
bool

False.

JudgmentPattern didactic-model

JudgmentPattern(*, family: FamilyId = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The judgments of one family whose evidence is kept.

PARAMETER DESCRIPTION
family

The family of the judgments.

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

RequestedEvidence didactic-model

RequestedEvidence(*, patterns: tuple[JudgmentPattern, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['requested'] = 'requested')

Bases: QiecModel

Keep the evidence of the judgments that match patterns.

PARAMETER DESCRIPTION
patterns

The judgments, at least one pattern and none repeated.

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

tag

Always "requested".

TYPE: str DEFAULT: 'requested'

keeps_forest property

keeps_forest: bool

Whether the packed forest is kept.

RETURNS DESCRIPTION
bool

False.

PackedForest didactic-model

PackedForest(*, tag: Literal['packed-forest'] = 'packed-forest')

Bases: QiecModel

Keep the derived hypergraph with occurrences and grounded instances.

Its tree unfoldings from a judgment correspond one to one to the derivations of the judgment when it is acyclic, so every linear fold can be computed from it.

PARAMETER DESCRIPTION
tag

Always "packed-forest".

TYPE: str DEFAULT: 'packed-forest'

keeps_forest property

keeps_forest: bool

Whether the packed forest is kept.

RETURNS DESCRIPTION
bool

True.

Support didactic-model

Support(*, tag: Literal['support'] = 'support')

Bases: _Observable

Whether the detailed meaning has a derivation of nonzero weight.

Support is a homomorphism to the Boolean algebra when no sum of nonzero weights and no product of nonzero weights is zero.

PARAMETER DESCRIPTION
tag

Always "support".

TYPE: str DEFAULT: 'support'

differentiable property

differentiable: bool

Whether the result has a derivative in the weights.

RETURNS DESCRIPTION
bool

False: it is a truth value.

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws, no zero sums and no zero divisors.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws, no zero sums and no zero divisors.
    """
    return requirements((*SEMIRING_LAWS, ZERO_SUM_FREE, NO_ZERO_DIVISORS), algebra)

Weight didactic-model

Weight(*, tag: Literal['weight'] = 'weight')

Bases: _Observable

The sum of the weights of all derivations.

PARAMETER DESCRIPTION
tag

Always "weight".

TYPE: str DEFAULT: 'weight'

Best didactic-model

Best(*, tag: Literal['best'] = 'best')

Bases: _Observable

The best derivation's weight and the derivation.

PARAMETER DESCRIPTION
tag

Always "best".

TYPE: str DEFAULT: 'best'

selects property

selects: bool

Whether the result selects among alternatives.

RETURNS DESCRIPTION
bool

True.

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws and a selective sum.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws and a selective sum.
    """
    return requirements((*SEMIRING_LAWS, PLUS_SELECTIVE), algebra)

KBest didactic-model

KBest(*, k: int, tag: Literal['k-best'] = 'k-best')

Bases: _Observable

The k best derivations.

PARAMETER DESCRIPTION
k

How many, at least one.

TYPE: int

tag

Always "k-best".

TYPE: str DEFAULT: 'k-best'

selects property

selects: bool

Whether the result selects among alternatives.

RETURNS DESCRIPTION
bool

True.

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws, a selective sum and superior rules.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws, a selective sum and superior rules.
    """
    return requirements((*SEMIRING_LAWS, PLUS_SELECTIVE, SUPERIOR), algebra)

Outcome didactic-model

Outcome(*, key: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['outcome'] = 'outcome')

Bases: _Observable

The weight of each outcome: the pushforward along a key.

PARAMETER DESCRIPTION
key

The computation that maps a meaning to its outcome, with a decidable equality on outcomes.

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

tag

Always "outcome".

TYPE: str DEFAULT: 'outcome'

ProjectedWeightRows didactic-model

ProjectedWeightRows(*, judgment: FamilyId = field(opaque=True, extras=OPAQUE_BY_VALUE), position: int, field: IndexBinder = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['projected-weight-rows'] = 'projected-weight-rows')

Bases: _Observable

The weights of items grouped by exact equality at one judgment index.

PARAMETER DESCRIPTION
judgment

The checked family of the items whose weights are grouped.

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

position

The zero-based position in that judgment's ordered index telescope.

TYPE: int

field

The binder and sort declared at that position.

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

tag

Always "projected-weight-rows".

TYPE: Literal['projected-weight-rows'] DEFAULT: 'projected-weight-rows'

NormalizedWeightRows didactic-model

NormalizedWeightRows(*, source: Weight | Outcome | ProjectedWeightRows = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['normalized-weight-rows'] = 'normalized-weight-rows')

Bases: _Observable

A finite collection of weight rows divided by their common total.

The source fixes the row key. All supported rows share one divisor. The normalization is defined only for positive total mass.

PARAMETER DESCRIPTION
source

The unnormalized item weights or their checked pushforward.

TYPE: Weight | Outcome | ProjectedWeightRows DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

Always "normalized-weight-rows".

TYPE: Literal['normalized-weight-rows'] DEFAULT: 'normalized-weight-rows'

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

Require the source weighting laws and division by a nonzero total.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The source requirements followed by division.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """Require the source weighting laws and division by a nonzero total.

    Parameters
    ----------
    algebra
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The source requirements followed by division.
    """
    return (*self.source.requirements(algebra), *requirements((DIVISION,), algebra))

WeightedProofRows didactic-model

WeightedProofRows(*, normalized: bool = False, tag: Literal['weighted-proof-rows'] = 'weighted-proof-rows')

Bases: _Observable

The positive-weight derivations and their individual log masses.

Rows preserve proof occurrences, even if their checked proof values coincide. A normalized result divides their weights by the common positive total mass.

PARAMETER DESCRIPTION
normalized

Whether to normalize the returned proof weights.

TYPE: bool DEFAULT: False

tag

Always "weighted-proof-rows".

TYPE: Literal['weighted-proof-rows'] DEFAULT: 'weighted-proof-rows'

needs_finite_derivations property

needs_finite_derivations: bool

Whether a guaranteed result lists finitely many derivations.

RETURNS DESCRIPTION
bool

True. The observable lists all supported proof occurrences.

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws needed to assign the proof weights.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

An associative ordered product with a unit and absorbing zero. Normalization also needs an associative commutative sum and division.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws needed to assign the proof weights.

    Parameters
    ----------
    algebra
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        An associative ordered product with a unit and absorbing zero.
        Normalization also needs an associative commutative sum and division.
    """
    laws = (
        (
            TIMES_ASSOCIATIVE,
            TIMES_UNIT,
            ZERO_ANNIHILATES,
            PLUS_ASSOCIATIVE,
            PLUS_COMMUTATIVE,
            DIVISION,
        )
        if self.normalized
        else (TIMES_ASSOCIATIVE, TIMES_UNIT, ZERO_ANNIHILATES)
    )
    return requirements(laws, algebra)

BooleanProofWeightRows didactic-model

BooleanProofWeightRows(*, normalized: bool = False, tag: Literal['boolean-proof-weight-rows'] = 'boolean-proof-weight-rows')

Bases: _Observable

The mass of each positive Boolean meaning of the proofs.

The interpretation supplies one truth value per lexical word and a truth table over each rule's ordered premise meanings. The result has at most one row for each Boolean value.

PARAMETER DESCRIPTION
normalized

Whether to divide the two masses by their common positive total.

TYPE: bool DEFAULT: False

tag

Always "boolean-proof-weight-rows".

TYPE: Literal['boolean-proof-weight-rows'] DEFAULT: 'boolean-proof-weight-rows'

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

Require finite sums of products and optional division.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws, and division for a normalized result.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """Require finite sums of products and optional division.

    Parameters
    ----------
    algebra
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws, and division for a normalized result.
    """
    laws = (*SEMIRING_LAWS, DIVISION) if self.normalized else SEMIRING_LAWS
    return requirements(laws, algebra)

Statistic didactic-model

Statistic(*, statistic: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['statistic'] = 'statistic')

Bases: _Observable

The weight and the expectation of a statistic, in a semimodule.

PARAMETER DESCRIPTION
statistic

The computation of the statistic of a derivation.

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

tag

Always "statistic".

TYPE: str DEFAULT: 'statistic'

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws and the semimodule action.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws and the semimodule action.
    """
    return requirements((*SEMIRING_LAWS, SEMIMODULE_ACTION), algebra)

Marginal didactic-model

Marginal(*, normalized: bool = False, tag: Literal['marginal'] = 'marginal')

Bases: _Observable

The derivative of the weight in each occurrence weight.

PARAMETER DESCRIPTION
normalized

Whether the marginals are divided by the total weight.

TYPE: bool DEFAULT: False

tag

Always "marginal".

TYPE: str DEFAULT: 'marginal'

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws, and division when normalized.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws, and division when normalized.
    """
    laws = (*SEMIRING_LAWS, DIVISION) if self.normalized else SEMIRING_LAWS
    return requirements(laws, algebra)

Sample didactic-model

Sample(*, n: int, tag: Literal['sample'] = 'sample')

Bases: _Observable

Derivations drawn in proportion to their weight.

PARAMETER DESCRIPTION
n

How many draws, at least one.

TYPE: int

tag

Always "sample".

TYPE: str DEFAULT: 'sample'

differentiable property

differentiable: bool

Whether the result has a derivative in the weights.

RETURNS DESCRIPTION
bool

False: a draw has none. The gradient of an expectation is a statistic with an estimator.

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws and division, which normalizing needs.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws and division, which normalizing needs.
    """
    return requirements((*SEMIRING_LAWS, DIVISION), algebra)

Fold didactic-model

Fold(*, fold: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['fold'] = 'fold')

Bases: _Observable

A fold of the detailed meaning that is linear in the weights.

PARAMETER DESCRIPTION
fold

The fold.

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

tag

Always "fold".

TYPE: str DEFAULT: 'fold'

needs_forest property

needs_forest: bool

Whether the result needs the packed forest.

RETURNS DESCRIPTION
bool

True.

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

The semiring laws, and linearity of the fold.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        The semiring laws, and linearity of the fold.
    """
    return (
        *requirements(SEMIRING_LAWS, algebra),
        Requirement(
            law=FOLD_LINEAR,
            subject=ClaimSubject(kind="computation", name=str(self.fold)),
        ),
    )

NonlinearFold didactic-model

NonlinearFold(*, fold: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['nonlinear-fold'] = 'nonlinear-fold')

Bases: _Observable

Any fold of the detailed meaning, linear or not.

No aggregate summarizes it in general: the alternatives -1 and 1 sum to 0 and have squares summing to 2. It needs every derivation, so a guaranteed result needs finitely many and the packed forest.

PARAMETER DESCRIPTION
fold

The fold.

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

tag

Always "nonlinear-fold".

TYPE: str DEFAULT: 'nonlinear-fold'

needs_forest property

needs_forest: bool

Whether the result needs the packed forest.

RETURNS DESCRIPTION
bool

True.

needs_finite_derivations property

needs_finite_derivations: bool

Whether a guaranteed result needs finitely many derivations.

RETURNS DESCRIPTION
bool

True.

Forest didactic-model

Forest(*, tag: Literal['forest'] = 'forest')

Bases: _Observable

The packed forest itself.

PARAMETER DESCRIPTION
tag

Always "forest".

TYPE: str DEFAULT: 'forest'

differentiable property

differentiable: bool

Whether the result has a derivative in the weights.

RETURNS DESCRIPTION
bool

False: it is a structure.

needs_forest property

needs_forest: bool

Whether the result needs the packed forest.

RETURNS DESCRIPTION
bool

True.

requirements

requirements(algebra: ClaimSubject) -> tuple[Requirement, ...]

The laws the result needs.

PARAMETER DESCRIPTION
algebra

The weight algebra.

TYPE: ClaimSubject

RETURNS DESCRIPTION
tuple of Requirement

None: the forest is the derivations, not their weights.

Source code in src/quivers/qiec/contracts.py
def requirements(self, algebra: ClaimSubject) -> tuple[Requirement, ...]:
    """The laws the result needs.

    Parameters
    ----------
    algebra : ClaimSubject
        The weight algebra.

    Returns
    -------
    tuple of Requirement
        None: the forest is the derivations, not their weights.
    """
    return ()

QuerySpec didactic-model

QuerySpec(*, presentation: PresentationId = field(opaque=True, extras=OPAQUE_BY_VALUE), interpretation: InterpretationId = field(opaque=True, extras=OPAQUE_BY_VALUE), observable: Observable = field(opaque=True, extras=OPAQUE_BY_VALUE), input_types: tuple[TypeExpr, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), differentiate_with_respect_to: tuple[ParameterId | OccurrenceId, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), batch_axes: tuple[str, ...] = (), retention: Retention = field(default=NoRetention(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

What a query asks of a presentation under an interpretation.

PARAMETER DESCRIPTION
presentation

The rule presentation.

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

interpretation

The interpretation of its rules.

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

observable

What is observed.

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

input_types

The types of the inputs.

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

differentiate_with_respect_to

The parameters and occurrences differentiated, in the order of the gradient, without repeats.

TYPE: tuple of ParameterId or OccurrenceId DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

batch_axes

Names of batch axes, without repeats.

TYPE: tuple of str DEFAULT: ()

retention

The provenance kept.

TYPE: Retention DEFAULT: field(default=NoRetention(), opaque=True, extras=OPAQUE_BY_VALUE)

RAISES DESCRIPTION
ValidationError

If a differentiated input or a batch axis repeats.

Phase

Bases: str, Enum

A phase of a computation whose work is bounded and counted apart.

ComputationModel didactic-model

ComputationModel(*, name: str, description: str)

Bases: QiecModel

The model of computation a bound is stated in.

PARAMETER DESCRIPTION
name

A short name.

TYPE: str

description

What costs one unit.

TYPE: str

ComplexityParameter didactic-model

ComplexityParameter(*, name: str, meaning: str)

Bases: QiecModel

A named size that bounds are stated in.

PARAMETER DESCRIPTION
name

An identifier, such as V, E or width.

TYPE: str

meaning

What it counts.

TYPE: str

ProvedOptimal didactic-model

ProvedOptimal(*, lower_bound: str, model: ComputationModel = field(opaque=True, extras=OPAQUE_BY_VALUE), sources: tuple[Citation, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['proved-optimal'] = 'proved-optimal')

Bases: QiecModel

The bound is optimal: a lower bound matches it in a stated model.

PARAMETER DESCRIPTION
lower_bound

The lower bound, in the parameters of the claim, without the asymptotic symbol. It must equal the bound's expression.

TYPE: str

model

The model of the lower bound.

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

sources

Where it is proved, at least one.

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

tag

Always "proved-optimal".

TYPE: str DEFAULT: 'proved-optimal'

Conditional didactic-model

Conditional(*, hypothesis: str, sources: tuple[Citation, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['conditional'] = 'conditional')

Bases: QiecModel

The bound is optimal if a stated hypothesis holds.

PARAMETER DESCRIPTION
hypothesis

The hypothesis, such as a conjecture of fine-grained complexity.

TYPE: str

sources

Where the conditional lower bound is proved, at least one.

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

tag

Always "conditional".

TYPE: str DEFAULT: 'conditional'

BestKnown didactic-model

BestKnown(*, sources: tuple[Citation, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['best-known'] = 'best-known')

Bases: QiecModel

The bound is the best published, with no matching lower bound.

PARAMETER DESCRIPTION
sources

Where it is published, at least one.

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

tag

Always "best-known".

TYPE: str DEFAULT: 'best-known'

Unresolved didactic-model

Unresolved(*, obligation: str, tag: Literal['unresolved'] = 'unresolved')

Bases: QiecModel

Whether the bound can be improved is open: a research obligation.

PARAMETER DESCRIPTION
obligation

What remains to be shown.

TYPE: str

tag

Always "unresolved".

TYPE: str DEFAULT: 'unresolved'

Deficient didactic-model

Deficient(*, better_bound: str, justification: str, reviewed_by: str, sources: tuple[Citation, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['deficient'] = 'deficient')

Bases: QiecModel

A better bound is known, and a reviewed reason keeps this one.

PARAMETER DESCRIPTION
better_bound

The better bound, in the parameters of the claim.

TYPE: str

justification

Why this bound is kept, and in which regime of parameters.

TYPE: str

reviewed_by

Who reviewed the justification.

TYPE: str

sources

Where the better bound is published, at least one.

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

tag

Always "deficient".

TYPE: str DEFAULT: 'deficient'

ComplexityBound didactic-model

ComplexityBound(*, phase: Phase = field(opaque=True, extras=OPAQUE_BY_VALUE), resource: Literal['time', 'space'], expression: str, status: OptimalityStatus = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An upper bound on one resource of one phase.

PARAMETER DESCRIPTION
phase

The phase.

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

resource

"time" or "space".

TYPE: str

expression

The bound in the parameters of the claim, without the asymptotic symbol: V + E stands for O(V + E).

TYPE: str

status

How it compares with what is known.

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

PhaseInapplicable didactic-model

PhaseInapplicable(*, phase: Phase = field(opaque=True, extras=OPAQUE_BY_VALUE), reason: str)

Bases: QiecModel

A phase that the query class does not have.

PARAMETER DESCRIPTION
phase

The phase.

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

reason

Why it does not apply.

TYPE: str

ComplexityClaim didactic-model

ComplexityClaim(*, query: str, parameters: tuple[ComplexityParameter, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), model: ComputationModel = field(opaque=True, extras=OPAQUE_BY_VALUE), bounds: tuple[ComplexityBound, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), inapplicable: tuple[PhaseInapplicable, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[str, ...] = ())

Bases: QiecModel

Bounds on the work of a query class, with their optimality status.

PARAMETER DESCRIPTION
query

The query class.

TYPE: str

parameters

The sizes the bounds are stated in.

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

model

The model of the bounds.

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

bounds

A time and a space bound for every phase that applies.

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

inapplicable

The phases that do not apply.

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

conditions

What the bounds need of the algebra and the input.

TYPE: tuple of str DEFAULT: ()

GroupingRecord didactic-model

GroupingRecord(*, handler: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE), operation: OperationId = field(opaque=True, extras=OPAQUE_BY_VALUE), row_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), key_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), empty: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), entry: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), normalized: bool, input_rows: int, distinct_keys: int, positive_rows: int, algebra: ClaimSubject, claims: tuple[LawClaim, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), complexity: ComplexityClaim = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The checked reduction of supplied log weights by exact structural keys.

Each input row contributes once to its key. The result keeps one row per positive key in first-occurrence order. A normalized result divides all its masses by their positive common total.

PARAMETER DESCRIPTION
handler

The installed handler and reached grouping operation.

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

operation

The installed handler and reached grouping operation.

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

row_type

The checked closed row-list and key types.

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

key_type

The checked closed row-list and key types.

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

empty

The exact constructors used for the input and output row list.

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

entry

The exact constructors used for the input and output row list.

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

normalized

Whether the successful result divides by a common positive total.

TYPE: bool

input_rows

The supplied rows, all distinct keys, and the positive output rows.

TYPE: int

distinct_keys

The supplied rows, all distinct keys, and the positive output rows.

TYPE: int

positive_rows

The supplied rows, all distinct keys, and the positive output rows.

TYPE: int

algebra

The weight algebra and its available law claims.

TYPE: ClaimSubject

claims

The weight algebra and its available law claims.

TYPE: ClaimSubject

complexity

Bounds for the reduction from supplied rows, including its weight derivative.

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

requirements

requirements() -> tuple[Requirement, ...]

State the laws used to aggregate keys and preserve positive support.

RETURNS DESCRIPTION
tuple of Requirement

The additive laws and zero-sum-freeness, with division when normalized.

Source code in src/quivers/qiec/contracts.py
def requirements(self) -> tuple[Requirement, ...]:
    """State the laws used to aggregate keys and preserve positive support.

    Returns
    -------
    tuple of Requirement
        The additive laws and zero-sum-freeness, with division when normalized.
    """
    laws = (PLUS_ASSOCIATIVE, PLUS_COMMUTATIVE, PLUS_UNIT, ZERO_SUM_FREE)
    return requirements(
        (*laws, DIVISION) if self.normalized else laws, self.algebra
    )

WorkField

Bases: str, Enum

A counter of a work report.

WorkReport didactic-model

WorkReport(*, phase: Phase = field(opaque=True, extras=OPAQUE_BY_VALUE), iterations: int = 0, scalar_sums: int = 0, scalar_products: int = 0, scalar_divisions: int = 0, star_pivots: int = 0, exact_operations: int = 0, key_comparisons: int = 0, hash_operations: int = 0, product_states: int = 0, arcs_visited: int = 0, elements_allocated: int = 0, peak_live_elements: int = 0, peak_bytes: int = 0, elements_saved_for_backward: int = 0, provenance_records: int = 0, nodes_validated: int = 0, nodes_instantiated: int = 0, cache_hits: int = 0, cache_invalidations: int = 0, seconds: Rational | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), measured: tuple[WorkField, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Counters of the work of one phase of a run.

Counts are elements inside tensor operations, not kernel launches.

PARAMETER DESCRIPTION
phase

The phase counted.

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

iterations

Solver iterations.

TYPE: int DEFAULT: 0

scalar_sums

Scalar sums.

TYPE: int DEFAULT: 0

scalar_products

Scalar products.

TYPE: int DEFAULT: 0

scalar_divisions

Scalar divisions outside closures of one element.

TYPE: int DEFAULT: 0

star_pivots

Pivots of star computations: closures of one element, each one operation of the algebra, whatever it computes inside.

TYPE: int DEFAULT: 0

exact_operations

Rational or interval updates of an exact or enclosed decision, run when rounding alone cannot decide.

TYPE: int DEFAULT: 0

key_comparisons

Comparisons of keys.

TYPE: int DEFAULT: 0

hash_operations

Hash computations and lookups.

TYPE: int DEFAULT: 0

product_states

Product states created.

TYPE: int DEFAULT: 0

arcs_visited

Arcs visited.

TYPE: int DEFAULT: 0

elements_allocated

Elements allocated.

TYPE: int DEFAULT: 0

peak_live_elements

Elements live at once, at most.

TYPE: int DEFAULT: 0

peak_bytes

Bytes live at once, at most.

TYPE: int DEFAULT: 0

elements_saved_for_backward

Elements saved for the backward pass.

TYPE: int DEFAULT: 0

provenance_records

Provenance records kept.

TYPE: int DEFAULT: 0

nodes_validated

Graph nodes validated.

TYPE: int DEFAULT: 0

nodes_instantiated

Graph nodes instantiated.

TYPE: int DEFAULT: 0

cache_hits

Cache hits.

TYPE: int DEFAULT: 0

cache_invalidations

Cache invalidations.

TYPE: int DEFAULT: 0

seconds

Wall time, when measured.

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

measured

The counters the producer counted, in the order of WorkField, each once; measuring builds it. A counter outside it is not a count of zero but no count at all, so a cost claim is never checked against it.

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

scalar_work property

scalar_work: int

Scalar sums, products and divisions.

RETURNS DESCRIPTION
int

Their total.

UnmeasuredWork

UnmeasuredWork(field: WorkField, reason: str)

Bases: ValueError

A cost claim bounds a counter the work report did not count.

PARAMETER DESCRIPTION
field

The counter.

TYPE: WorkField

reason

What was being checked.

TYPE: str

Source code in src/quivers/qiec/contracts.py
def __init__(self, field: WorkField, reason: str) -> None:
    super().__init__(f"{field.value} is not measured: {reason}")
    self.field = field
    self.reason = reason

Attainment didactic-model

Attainment(*, guarantee: Guarantee = field(opaque=True, extras=OPAQUE_BY_VALUE), metric: Metric = field(opaque=True, extras=OPAQUE_BY_VALUE), rounding: Rational | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), derivative: DerivativeSemantics = field(default=NOT_DIFFERENTIATED, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

What a result reached: its guarantee, metric, rounding and derivative.

PARAMETER DESCRIPTION
guarantee

The guarantee reached. A certified bound carries its certificate.

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

metric

The metric of the guarantee.

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

rounding

A bound on the rounding error in the metric, or None when unknown.

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

derivative

The derivative reached.

TYPE: DerivativeSemantics DEFAULT: field(default=NOT_DIFFERENTIATED, opaque=True, extras=OPAQUE_BY_VALUE)

total_bound property

total_bound: Fraction | None

The bound with rounding included, when both parts are known.

RETURNS DESCRIPTION
Fraction or None

The certified or exact bound plus the rounding bound, or None when the guarantee has no bound that holds on every run or the rounding is unknown.

ArgumentBound didactic-model

ArgumentBound(*, metric: Metric = field(opaque=True, extras=OPAQUE_BY_VALUE), lipschitz: Rational | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), affine: bool = False)

Bases: QiecModel

What an operation promises about one of its arguments.

PARAMETER DESCRIPTION
metric

The metric of the argument the constant is stated in.

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

lipschitz

A constant L with d(g(.., x, ..), g(.., y, ..)) <= L d(x, y) for arguments that differ only here, on a region that holds the computed and the target values; None when there is none.

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

affine

Whether the operation is affine in this argument, which keeps unbiased estimates unbiased.

TYPE: bool DEFAULT: False

OperationBound didactic-model

OperationBound(*, name: str, arguments: tuple[ArgumentBound, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), metric: Metric = field(opaque=True, extras=OPAQUE_BY_VALUE), rounding: Rational | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), derivative: DerivativeSemantics = field(default=DerivativeSemantics(), opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[str, ...] = ())

Bases: QiecModel

What an operation that combines results promises about them.

PARAMETER DESCRIPTION
name

The operation.

TYPE: str

arguments

One per argument.

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

metric

The metric of the result.

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

rounding

A bound on the operation's own rounding error, or None.

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

derivative

The derivative of the operation itself, such as a tie rule for a maximum or none for a threshold.

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

conditions

Where the constants hold.

TYPE: tuple of str DEFAULT: ()

Completed didactic-model

Completed(*, tag: Literal['completed'] = 'completed')

Bases: QiecModel

The method ran to its end.

PARAMETER DESCRIPTION
tag

Always "completed".

TYPE: str DEFAULT: 'completed'

early property

early: bool

Whether the run stopped before its method ended.

RETURNS DESCRIPTION
bool

False.

BudgetExhausted didactic-model

BudgetExhausted(*, resource: Literal['iterations', 'scalar_work', 'states', 'elements', 'bytes', 'seconds'], limit: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['budget-exhausted'] = 'budget-exhausted')

Bases: QiecModel

The run stopped because a resource limit was reached.

PARAMETER DESCRIPTION
resource

The limit, a field of ResourceBudget.

TYPE: str

limit

Its value.

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

tag

Always "budget-exhausted".

TYPE: str DEFAULT: 'budget-exhausted'

early property

early: bool

Whether the run stopped before its method ended.

RETURNS DESCRIPTION
bool

True.

ControlReached didactic-model

ControlReached(*, control: str, value: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['control-reached'] = 'control-reached')

Bases: QiecModel

The run stopped because a control was reached, such as a residual.

A residual below a tolerance is a diagnostic, not a certificate.

PARAMETER DESCRIPTION
control

The control.

TYPE: str

value

The diagnostic when it stopped.

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

tag

Always "control-reached".

TYPE: str DEFAULT: 'control-reached'

early property

early: bool

Whether the run stopped before its method ended.

RETURNS DESCRIPTION
bool

True.

ContractField

Bases: str, Enum

A requirement of an accuracy contract that a run can fail.

AccuracyReport didactic-model

AccuracyReport(*, attainment: Attainment = field(opaque=True, extras=OPAQUE_BY_VALUE), stop: StopReason = field(default=Completed(), opaque=True, extras=OPAQUE_BY_VALUE), unmet: tuple[ContractField, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), derivatives: DerivativeReport = field(default=DerivativeReport(), opaque=True, extras=OPAQUE_BY_VALUE), work: tuple[WorkReport, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), claims: tuple[LawClaim, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

What a run reached, why it stopped, and what it cost.

A derivative report of a run is the derivatives field, and its summary is the derivative of the attainment.

PARAMETER DESCRIPTION
attainment

What the result reached.

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

stop

Why the run stopped.

TYPE: StopReason DEFAULT: field(default=Completed(), opaque=True, extras=OPAQUE_BY_VALUE)

unmet

The requirements not met.

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

derivatives

The derivative of each output and input.

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

work

The work of each phase, one report per phase.

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

claims

Every law claim the run used.

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

RAISES DESCRIPTION
ValidationError

If a phase has two work reports, or the attainment's derivative is not the summary of the derivative report.

Unestablished didactic-model

Unestablished(*, value: HeldValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY), report: AccuracyReport = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A value whose contract was not met, with the report that says why.

It is not a weight, a tensor or a number, and nothing that expects one accepts it.

PARAMETER DESCRIPTION
value

The value the run computed.

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

report

What it reached, with the unmet requirements.

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

ContractNotMet

ContractNotMet(report: AccuracyReport)

Bases: ValueError

A run did not meet its contract, and the contract says to refuse.

PARAMETER DESCRIPTION
report

What the run reached.

TYPE: AccuracyReport

Source code in src/quivers/qiec/contracts.py
def __init__(self, report: AccuracyReport) -> None:
    names = ", ".join(field.value for field in report.unmet)
    super().__init__(f"the contract is not met: {names}")
    self.report = report

RefusalCode

Bases: str, Enum

Why a combination of contract records is inadmissible.

Refusal didactic-model

Refusal(*, code: RefusalCode = field(opaque=True, extras=OPAQUE_BY_VALUE), reason: str)

Bases: QiecModel

One reason a combination is inadmissible.

PARAMETER DESCRIPTION
code

The kind of reason.

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

reason

The reason, with the records it concerns.

TYPE: str

InadmissibleContract

InadmissibleContract(refusals: tuple[Refusal, ...])

Bases: ValueError

A query, its recursion, its contract and its claims do not fit.

PARAMETER DESCRIPTION
refusals

Every reason.

TYPE: tuple of Refusal

Source code in src/quivers/qiec/contracts.py
def __init__(self, refusals: tuple[Refusal, ...]) -> None:
    super().__init__(
        "; ".join(f"{item.code.value}: {item.reason}" for item in refusals)
    )
    self.refusals = refusals

InadmissibleReport

InadmissibleReport(refusals: tuple[Refusal, ...])

Bases: ValueError

A report claims what its run cannot show, or contradicts its contract.

PARAMETER DESCRIPTION
refusals

Every reason.

TYPE: tuple of Refusal

Source code in src/quivers/qiec/contracts.py
def __init__(self, refusals: tuple[Refusal, ...]) -> None:
    super().__init__(
        "; ".join(f"{item.code.value}: {item.reason}" for item in refusals)
    )
    self.refusals = refusals

measuring

measuring(fields: Iterable[WorkField]) -> tuple[WorkField, ...]

Counters as a work report lists them: in the order of WorkField, each once.

PARAMETER DESCRIPTION
fields

The counters.

TYPE: Iterable of WorkField

RETURNS DESCRIPTION
tuple of WorkField

The listing.

Source code in src/quivers/qiec/contracts.py
def measuring(fields: Iterable[WorkField]) -> tuple[WorkField, ...]:
    """Counters as a work report lists them: in the order of `WorkField`, each once.

    Parameters
    ----------
    fields : Iterable of WorkField
        The counters.

    Returns
    -------
    tuple of WorkField
        The listing.
    """
    chosen = set(fields)
    return tuple(field for field in WorkField if field in chosen)

bounded_fields

bounded_fields(bound: ComplexityBound) -> frozenset[WorkField]

The counters a bound of the algebra-operations model bounds.

PARAMETER DESCRIPTION
bound

The bound.

TYPE: ComplexityBound

RETURNS DESCRIPTION
frozenset of WorkField

The time counters for a time bound, the space counters of its phase for a space bound.

Source code in src/quivers/qiec/contracts.py
def bounded_fields(bound: ComplexityBound) -> frozenset[WorkField]:
    """The counters a bound of the algebra-operations model bounds.

    Parameters
    ----------
    bound : ComplexityBound
        The bound.

    Returns
    -------
    frozenset of WorkField
        The time counters for a time bound, the space counters of its
        phase for a space bound.
    """
    if bound.resource == "time":
        return TIME_FIELDS
    return SPACE_FIELDS[bound.phase]

measured_total

measured_total(bound: ComplexityBound, report: WorkReport) -> int

The measured quantity a bound bounds: the time spent, or the space held.

PARAMETER DESCRIPTION
bound

The bound.

TYPE: ComplexityBound

report

The work of the bound's phase.

TYPE: WorkReport

RETURNS DESCRIPTION
int

The sum of the time counters, or the largest space counter.

RAISES DESCRIPTION
UnmeasuredWork

If a counter the bound bounds is not measured.

ValueError

If the report is of another phase.

Source code in src/quivers/qiec/contracts.py
def measured_total(bound: ComplexityBound, report: WorkReport) -> int:
    """The measured quantity a bound bounds: the time spent, or the space held.

    Parameters
    ----------
    bound : ComplexityBound
        The bound.
    report : WorkReport
        The work of the bound's phase.

    Returns
    -------
    int
        The sum of the time counters, or the largest space counter.

    Raises
    ------
    UnmeasuredWork
        If a counter the bound bounds is not measured.
    ValueError
        If the report is of another phase.
    """
    if report.phase is not bound.phase:
        raise ValueError(
            f"a {bound.phase.value} bound is checked against {report.phase.value} work"
        )
    fields = bounded_fields(bound)
    for field in sorted(fields, key=lambda item: item.value):
        if field not in report.measured:
            raise UnmeasuredWork(
                field,
                f"the {bound.phase.value} {bound.resource} bound {bound.expression}",
            )
    values = [getattr(report, field.value) for field in fields]
    return sum(values) if bound.resource == "time" else max(values)

compose

compose(parts: tuple[Attainment, ...], operation: OperationBound) -> Attainment

The attainment of an operation applied to results.

This is the composition law: the guarantee of the composite is the weakest of its parts, and a bound propagates through each part's Lipschitz constant. A part with a bound but no constant in its own metric makes the composite heuristic, and so does a heuristic part unless the operation is constant in it.

PARAMETER DESCRIPTION
parts

The attainment of each argument.

TYPE: tuple of Attainment

operation

What the operation promises.

TYPE: OperationBound

RETURNS DESCRIPTION
Attainment

The composite. Its bound is sum_i L_i e_i over the parts that are not exact, its rounding r + sum_i L_i r_i when every term is known, its failure probability the sum of the parts', and its derivative the weakest of the parts' and the operation's, with an unbiased estimate kept only through affine arguments.

RAISES DESCRIPTION
ValueError

If the number of parts is not the number of arguments, or the parts use different tie rules or estimate one site twice.

Source code in src/quivers/qiec/contracts.py
def compose(parts: tuple[Attainment, ...], operation: OperationBound) -> Attainment:
    """The attainment of an operation applied to results.

    This is the composition law: the guarantee of the composite is the
    weakest of its parts, and a bound propagates through each part's
    Lipschitz constant. A part with a bound but no constant in its own
    metric makes the composite heuristic, and so does a heuristic part
    unless the operation is constant in it.

    Parameters
    ----------
    parts : tuple of Attainment
        The attainment of each argument.
    operation : OperationBound
        What the operation promises.

    Returns
    -------
    Attainment
        The composite. Its bound is ``sum_i L_i e_i`` over the parts that
        are not exact, its rounding ``r + sum_i L_i r_i`` when every term
        is known, its failure probability the sum of the parts', and its
        derivative the weakest of the parts' and the operation's, with an
        unbiased estimate kept only through affine arguments.

    Raises
    ------
    ValueError
        If the number of parts is not the number of arguments, or the
        parts use different tie rules or estimate one site twice.
    """
    if len(parts) != len(operation.arguments):
        raise ValueError(
            f"{operation.name} takes {len(operation.arguments)} arguments, "
            f"got {len(parts)}"
        )
    pairs = tuple(zip(parts, operation.arguments, strict=True))
    usable = tuple(
        argument.lipschitz is not None and part.metric == argument.metric
        for part, argument in pairs
    )
    triangle = operation.metric.triangle_inequality
    derivative = _composed_derivative(parts, operation)
    rounding = None
    if (
        triangle
        and operation.rounding is not None
        and all(usable)
        and all(part.rounding is not None for part in parts)
    ):
        rounding = Rational.of(
            operation.rounding.fraction
            + sum(
                (_lipschitz(argument) * _rounding(part) for part, argument in pairs),
                Fraction(0),
            )
        )
    guarantee = _composed_guarantee(pairs, usable, operation, triangle)
    return Attainment(
        guarantee=guarantee,
        metric=operation.metric,
        rounding=rounding,
        derivative=derivative,
    )

attained_guarantee

attained_guarantee(stop: StopReason, method: Guarantee, certificate: Certificate | None) -> Guarantee

The guarantee a run may claim.

PARAMETER DESCRIPTION
stop

Why the run stopped.

TYPE: StopReason

method

The guarantee of the method when it runs to its end.

TYPE: Guarantee

certificate

A certificate the run computed, if any.

TYPE: Certificate or None

RETURNS DESCRIPTION
Guarantee

The method's guarantee when it completed. A run that stopped early claims the bound of its certificate, and without one it claims nothing: neither the budget nor the residual is a bound.

Source code in src/quivers/qiec/contracts.py
def attained_guarantee(
    stop: StopReason, method: Guarantee, certificate: Certificate | None
) -> Guarantee:
    """The guarantee a run may claim.

    Parameters
    ----------
    stop : StopReason
        Why the run stopped.
    method : Guarantee
        The guarantee of the method when it runs to its end.
    certificate : Certificate or None
        A certificate the run computed, if any.

    Returns
    -------
    Guarantee
        The method's guarantee when it completed. A run that stopped
        early claims the bound of its certificate, and without one it
        claims nothing: neither the budget nor the residual is a bound.
    """
    if not stop.early:
        return method
    if certificate is not None:
        return Certified(
            bound=Rational.of(certificate.bound),
            conditions=certificate.conditions,
            certificate=certificate,
        )
    return Heuristic(reason=f"stopped early by {stop.tag} without a certificate")

unmet_fields

unmet_fields(contract: AccuracyContract, attainment: Attainment, work: tuple[WorkReport, ...]) -> tuple[ContractField, ...]

The requirements of a contract that a run did not meet.

PARAMETER DESCRIPTION
contract

The contract.

TYPE: AccuracyContract

attainment

What the run reached.

TYPE: Attainment

work

Its work.

TYPE: tuple of WorkReport

RETURNS DESCRIPTION
tuple of ContractField

In the order of ContractField: the target's metric if it is another one, the guarantee if it is weaker, the rounding if it is unknown or above the contract's, the derivative if it is weaker, and the budget if the work exceeded it.

Source code in src/quivers/qiec/contracts.py
def unmet_fields(
    contract: AccuracyContract, attainment: Attainment, work: tuple[WorkReport, ...]
) -> tuple[ContractField, ...]:
    """The requirements of a contract that a run did not meet.

    Parameters
    ----------
    contract : AccuracyContract
        The contract.
    attainment : Attainment
        What the run reached.
    work : tuple of WorkReport
        Its work.

    Returns
    -------
    tuple of ContractField
        In the order of `ContractField`: the target's metric if it is
        another one, the guarantee if it is weaker, the rounding if it is
        unknown or above the contract's, the derivative if it is weaker,
        and the budget if the work exceeded it.
    """
    unmet: list[ContractField] = []
    if attainment.metric != contract.target.metric:
        unmet.append(ContractField.TARGET)
    if not _guarantee_meets(attainment.guarantee, contract.guarantee):
        unmet.append(ContractField.GUARANTEE)
    limit = contract.numerics.rounding
    if limit is not None and (
        attainment.rounding is None or attainment.rounding.fraction > limit.fraction
    ):
        unmet.append(ContractField.NUMERICS)
    if not attainment.derivative.at_least(contract.gradient):
        unmet.append(ContractField.GRADIENT)
    if _exceeded(contract.budget, work):
        unmet.append(ContractField.BUDGET)
    return tuple(unmet)

settle

settle(contract: AccuracyContract, value: T, report: AccuracyReport) -> T | Unestablished

Apply a contract's failure policy to a run's result.

PARAMETER DESCRIPTION
contract

The contract.

TYPE: AccuracyContract

value

The value the run computed.

TYPE: T

report

Its report.

TYPE: AccuracyReport

RETURNS DESCRIPTION
T or Unestablished

The value when the report meets the contract; otherwise the value wrapped as unestablished, when the contract says to return it.

RAISES DESCRIPTION
InadmissibleReport

If the report is inconsistent with the contract.

ContractNotMet

If the contract is not met and says to refuse.

Source code in src/quivers/qiec/contracts.py
def settle[T](
    contract: AccuracyContract, value: T, report: AccuracyReport
) -> T | Unestablished:
    """Apply a contract's failure policy to a run's result.

    Parameters
    ----------
    contract : AccuracyContract
        The contract.
    value : T
        The value the run computed.
    report : AccuracyReport
        Its report.

    Returns
    -------
    T or Unestablished
        The value when the report meets the contract; otherwise the value
        wrapped as unestablished, when the contract says to return it.

    Raises
    ------
    InadmissibleReport
        If the report is inconsistent with the contract.
    ContractNotMet
        If the contract is not met and says to refuse.
    """
    found = report_refusals(contract, report)
    if found:
        raise InadmissibleReport(found)
    if not report.unmet:
        return value
    if contract.on_failure is FailurePolicy.REFUSE:
        raise ContractNotMet(report)
    return Unestablished(value=value, report=report)

admissibility

admissibility(query: QuerySpec, recursion: Recursion, contract: AccuracyContract, *, algebra: ClaimSubject, claims: tuple[LawClaim, ...], uses: tuple[Requirement, ...] = ()) -> tuple[Refusal, ...]

Every reason a query, its recursion, contract and claims do not fit.

PARAMETER DESCRIPTION
query

The query.

TYPE: QuerySpec

recursion

How its system is solved.

TYPE: Recursion

contract

Its accuracy contract.

TYPE: AccuracyContract

algebra

Its weight algebra.

TYPE: ClaimSubject

claims

The law claims available.

TYPE: tuple of LawClaim

uses

Further laws the executor relies on, such as commutativity of the product for an elimination order.

TYPE: tuple of Requirement DEFAULT: ()

RETURNS DESCRIPTION
tuple of Refusal

Empty when the combination is admissible.

Source code in src/quivers/qiec/contracts.py
def admissibility(
    query: QuerySpec,
    recursion: Recursion,
    contract: AccuracyContract,
    *,
    algebra: ClaimSubject,
    claims: tuple[LawClaim, ...],
    uses: tuple[Requirement, ...] = (),
) -> tuple[Refusal, ...]:
    """Every reason a query, its recursion, contract and claims do not fit.

    Parameters
    ----------
    query : QuerySpec
        The query.
    recursion : Recursion
        How its system is solved.
    contract : AccuracyContract
        Its accuracy contract.
    algebra : ClaimSubject
        Its weight algebra.
    claims : tuple of LawClaim
        The law claims available.
    uses : tuple of Requirement
        Further laws the executor relies on, such as commutativity of
        the product for an elimination order.

    Returns
    -------
    tuple of Refusal
        Empty when the combination is admissible.
    """
    found: list[Refusal] = []
    observable = query.observable
    guaranteed = not isinstance(contract.guarantee, Heuristic)
    wanted = contract.gradient
    needed = (
        *observable.requirements(algebra),
        *requirements(recursion.laws(), algebra),
        *uses,
    )
    for requirement in dict.fromkeys(needed):
        matching = [
            claim
            for claim in claims
            if claim.law == requirement.law and claim.subject == requirement.subject
        ]
        if not matching:
            found.append(
                Refusal(
                    code=RefusalCode.MISSING_CLAIM,
                    reason=(
                        f"no claim that {requirement.law.name} holds of "
                        f"{requirement.subject.name}"
                    ),
                )
            )
        if matching and guaranteed and not any(c.established for c in matching):
            found.append(
                Refusal(
                    code=RefusalCode.CLAIM_NOT_ESTABLISHED,
                    reason=(
                        f"{requirement.law.name} of {requirement.subject.name} is "
                        f"only {matching[0].status.value}, which licenses no "
                        "guaranteed result"
                    ),
                )
            )
    if isinstance(contract.guarantee, Exact) and not recursion.finite_method:
        found.append(
            Refusal(
                code=RefusalCode.EXACT_WITHOUT_FINITE_METHOD,
                reason=f"no finite method computes a {recursion.tag} solution exactly",
            )
        )
    if not recursion.admits(wanted):
        found.append(
            Refusal(
                code=RefusalCode.DERIVATIVE_UNAVAILABLE,
                reason=(
                    f"a {recursion.tag} solution has no {wanted.kind} derivative "
                    "of the kind requested"
                ),
            )
        )
    if not wanted.missing and not query.differentiate_with_respect_to:
        found.append(
            Refusal(
                code=RefusalCode.GRADIENT_WITHOUT_INPUTS,
                reason="a derivative is requested with respect to nothing",
            )
        )
    if wanted.missing and query.differentiate_with_respect_to:
        found.append(
            Refusal(
                code=RefusalCode.INPUTS_WITHOUT_GRADIENT,
                reason="inputs are differentiated but the contract requests no derivative",
            )
        )
    if query.differentiate_with_respect_to and not observable.differentiable:
        found.append(
            Refusal(
                code=RefusalCode.OBSERVABLE_NOT_DIFFERENTIABLE,
                reason=f"a {observable.tag} result has no derivative",
            )
        )
    if observable.selects and not wanted.missing and wanted.tie_rule is None:
        found.append(
            Refusal(
                code=RefusalCode.SELECTION_WITHOUT_TIE_RULE,
                reason=f"a {observable.tag} derivative needs the tie rule it accepts",
            )
        )
    if observable.needs_forest and not query.retention.keeps_forest:
        found.append(
            Refusal(
                code=RefusalCode.FOREST_NOT_RETAINED,
                reason=f"a {observable.tag} result needs the packed forest",
            )
        )
    if (
        observable.needs_finite_derivations
        and guaranteed
        and not recursion.finite_derivations
    ):
        found.append(
            Refusal(
                code=RefusalCode.INFINITE_DERIVATIONS,
                reason=(
                    f"a guaranteed {observable.tag} result enumerates derivations, "
                    f"and a {recursion.tag} system can have infinitely many"
                ),
            )
        )
    if (
        isinstance(contract.guarantee, Certified)
        and contract.guarantee.certificate is not None
    ):
        found.append(
            Refusal(
                code=RefusalCode.REQUEST_WITH_CERTIFICATE,
                reason="a requested bound carries no certificate; a run shows it",
            )
        )
    names = [control.name for control in contract.controls]
    if len(set(names)) != len(names):
        found.append(
            Refusal(
                code=RefusalCode.DUPLICATE_CONTROL,
                reason="a control is set twice",
            )
        )
    return tuple(found)

check_admissible

check_admissible(query: QuerySpec, recursion: Recursion, contract: AccuracyContract, *, algebra: ClaimSubject, claims: tuple[LawClaim, ...], uses: tuple[Requirement, ...] = ()) -> None

Refuse a query, recursion, contract and claims that do not fit.

PARAMETER DESCRIPTION
query

The query.

TYPE: QuerySpec

recursion

How its system is solved.

TYPE: Recursion

contract

Its accuracy contract.

TYPE: AccuracyContract

algebra

Its weight algebra.

TYPE: ClaimSubject

claims

The law claims available.

TYPE: tuple of LawClaim

uses

Further laws the executor relies on.

TYPE: tuple of Requirement DEFAULT: ()

RAISES DESCRIPTION
InadmissibleContract

With every reason, if there is one.

Source code in src/quivers/qiec/contracts.py
def check_admissible(
    query: QuerySpec,
    recursion: Recursion,
    contract: AccuracyContract,
    *,
    algebra: ClaimSubject,
    claims: tuple[LawClaim, ...],
    uses: tuple[Requirement, ...] = (),
) -> None:
    """Refuse a query, recursion, contract and claims that do not fit.

    Parameters
    ----------
    query : QuerySpec
        The query.
    recursion : Recursion
        How its system is solved.
    contract : AccuracyContract
        Its accuracy contract.
    algebra : ClaimSubject
        Its weight algebra.
    claims : tuple of LawClaim
        The law claims available.
    uses : tuple of Requirement
        Further laws the executor relies on.

    Raises
    ------
    InadmissibleContract
        With every reason, if there is one.
    """
    found = admissibility(
        query, recursion, contract, algebra=algebra, claims=claims, uses=uses
    )
    if found:
        raise InadmissibleContract(found)

report_refusals

report_refusals(contract: AccuracyContract, report: AccuracyReport, recursion: Recursion | None = None) -> tuple[Refusal, ...]

Every reason a report claims what its run cannot show.

PARAMETER DESCRIPTION
contract

The contract of the run.

TYPE: AccuracyContract

report

Its report.

TYPE: AccuracyReport

recursion

How the run solved its system, when it has one.

TYPE: Recursion or None DEFAULT: None

RETURNS DESCRIPTION
tuple of Refusal

Empty when the report is admissible.

Source code in src/quivers/qiec/contracts.py
def report_refusals(
    contract: AccuracyContract,
    report: AccuracyReport,
    recursion: Recursion | None = None,
) -> tuple[Refusal, ...]:
    """Every reason a report claims what its run cannot show.

    Parameters
    ----------
    contract : AccuracyContract
        The contract of the run.
    report : AccuracyReport
        Its report.
    recursion : Recursion or None
        How the run solved its system, when it has one.

    Returns
    -------
    tuple of Refusal
        Empty when the report is admissible.
    """
    found: list[Refusal] = []
    attained = report.attainment.guarantee
    if report.stop.early and isinstance(attained, Exact):
        found.append(
            Refusal(
                code=RefusalCode.EARLY_STOP_LABELLED_EXACT,
                reason=f"a run stopped by {report.stop.tag} is not exact",
            )
        )
    claimed = attained.bound.fraction if isinstance(attained, Certified) else None
    certificate = attained.certificate if isinstance(attained, Certified) else None
    if claimed is not None and certificate is None:
        found.append(
            Refusal(
                code=RefusalCode.CERTIFIED_WITHOUT_CERTIFICATE,
                reason="an attained bound carries the certificate that shows it",
            )
        )
    if claimed is not None and certificate is not None and claimed < certificate.bound:
        found.append(
            Refusal(
                code=RefusalCode.BOUND_BELOW_CERTIFICATE,
                reason=(
                    f"the bound {claimed} is below the {certificate.bound} its "
                    f"{certificate.tag} shows"
                ),
            )
        )
    if isinstance(certificate, Argument) and not certificate.claim.established:
        found.append(
            Refusal(
                code=RefusalCode.ARGUMENT_NOT_ESTABLISHED,
                reason=(
                    f"the argument {certificate.claim.law.name} is only "
                    f"{certificate.claim.status.value}"
                ),
            )
        )
    if certificate is not None and not _certificate_metric(
        certificate, report.attainment.metric
    ):
        found.append(
            Refusal(
                code=RefusalCode.CERTIFICATE_METRIC,
                reason=(
                    f"a {certificate.tag} does not bound the "
                    f"{report.attainment.metric.tag} metric"
                ),
            )
        )
    if not isinstance(attained, Heuristic):
        weak = [claim for claim in report.claims if not claim.established]
        if weak:
            found.append(
                Refusal(
                    code=RefusalCode.USED_CLAIM_NOT_ESTABLISHED,
                    reason=(
                        f"the run used {weak[0].law.name}, only "
                        f"{weak[0].status.value}, for a guaranteed result"
                    ),
                )
            )
    if (
        recursion is not None
        and isinstance(attained, Exact)
        and not recursion.finite_method
    ):
        found.append(
            Refusal(
                code=RefusalCode.EXACT_FOR_INEXACT_RECURSION,
                reason=f"a {recursion.tag} solution is not exact",
            )
        )
    expected = unmet_fields(contract, report.attainment, report.work)
    if report.unmet != expected:
        found.append(
            Refusal(
                code=RefusalCode.UNMET_MISREPORTED,
                reason=(
                    f"the unmet requirements are {[f.value for f in expected]}, "
                    f"reported {[f.value for f in report.unmet]}"
                ),
            )
        )
    return tuple(found)

check_report

check_report(contract: AccuracyContract, report: AccuracyReport, recursion: Recursion | None = None) -> None

Refuse a report that claims what its run cannot show.

PARAMETER DESCRIPTION
contract

The contract of the run.

TYPE: AccuracyContract

report

Its report.

TYPE: AccuracyReport

recursion

How the run solved its system, when it has one.

TYPE: Recursion or None DEFAULT: None

RAISES DESCRIPTION
InadmissibleReport

With every reason, if there is one.

Source code in src/quivers/qiec/contracts.py
def check_report(
    contract: AccuracyContract,
    report: AccuracyReport,
    recursion: Recursion | None = None,
) -> None:
    """Refuse a report that claims what its run cannot show.

    Parameters
    ----------
    contract : AccuracyContract
        The contract of the run.
    report : AccuracyReport
        Its report.
    recursion : Recursion or None
        How the run solved its system, when it has one.

    Raises
    ------
    InadmissibleReport
        With every reason, if there is one.
    """
    found = report_refusals(contract, report, recursion)
    if found:
        raise InadmissibleReport(found)

complexity_refusals

complexity_refusals(claim: ComplexityClaim) -> tuple[Refusal, ...]

Every reason a complexity claim is incomplete or unsupported.

PARAMETER DESCRIPTION
claim

The claim.

TYPE: ComplexityClaim

RETURNS DESCRIPTION
tuple of Refusal

Empty when every phase has a time and a space bound or is declared inapplicable (not both), every bound uses only the declared parameters, and every optimality proof has a lower bound equal to its bound.

Source code in src/quivers/qiec/contracts.py
def complexity_refusals(claim: ComplexityClaim) -> tuple[Refusal, ...]:
    """Every reason a complexity claim is incomplete or unsupported.

    Parameters
    ----------
    claim : ComplexityClaim
        The claim.

    Returns
    -------
    tuple of Refusal
        Empty when every phase has a time and a space bound or is
        declared inapplicable (not both), every bound uses only the
        declared parameters, and every optimality proof has a lower bound
        equal to its bound.
    """
    found: list[Refusal] = []
    declared = {parameter.name for parameter in claim.parameters}
    inapplicable = Counter(item.phase for item in claim.inapplicable)
    present = Counter((bound.phase, bound.resource) for bound in claim.bounds)
    for phase in Phase:
        resources = [present[(phase, resource)] for resource in ("time", "space")]
        bounded = resources == [1, 1]
        absent = resources == [0, 0] and inapplicable[phase] == 1
        if bounded == absent or (bounded and inapplicable[phase]):
            found.append(
                Refusal(
                    code=RefusalCode.INCOMPLETE_CLAIM,
                    reason=(
                        f"the {phase.value} phase needs one time and one space "
                        "bound, or one declaration that it does not apply"
                    ),
                )
            )
    for bound in claim.bounds:
        status = bound.status
        expressions = [bound.expression]
        if isinstance(status, ProvedOptimal):
            expressions.append(status.lower_bound)
        if isinstance(status, Deficient):
            expressions.append(status.better_bound)
        unknown = sorted(
            set().union(*(_identifiers(item) for item in expressions)) - declared
        )
        if unknown:
            found.append(
                Refusal(
                    code=RefusalCode.UNDECLARED_PARAMETER,
                    reason=(
                        f"the {bound.phase.value} {bound.resource} bound uses "
                        f"{unknown}, which the claim does not declare"
                    ),
                )
            )
        if isinstance(status, ProvedOptimal) and _normal(status.lower_bound) != _normal(
            bound.expression
        ):
            found.append(
                Refusal(
                    code=RefusalCode.LOWER_BOUND_MISMATCH,
                    reason=(
                        f"the lower bound {status.lower_bound} does not match the "
                        f"{bound.phase.value} {bound.resource} bound {bound.expression}"
                    ),
                )
            )
    return tuple(found)

check_complexity

check_complexity(claim: ComplexityClaim) -> None

Refuse an incomplete or unsupported complexity claim.

PARAMETER DESCRIPTION
claim

The claim.

TYPE: ComplexityClaim

RAISES DESCRIPTION
InadmissibleContract

With every reason, if there is one.

Source code in src/quivers/qiec/contracts.py
def check_complexity(claim: ComplexityClaim) -> None:
    """Refuse an incomplete or unsupported complexity claim.

    Parameters
    ----------
    claim : ComplexityClaim
        The claim.

    Raises
    ------
    InadmissibleContract
        With every reason, if there is one.
    """
    found = complexity_refusals(claim)
    if found:
        raise InadmissibleContract(found)