Skip to main content

omnibias.core.realization.polynomial

0.5.0rc1Release candidatePython >=3.10Apache-2.0

Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.

import omnibias.core.realization.polynomial
Module contract & mathematical conventions

Exact, budgeted coefficient maps of finite polynomial neural networks.

These are polynomials in the network parameters, not the Riccati polynomials in an activation value. No floating-point reconstruction is implicit.

Shared formulas do not imply universal floating-point identity. Verify dtype, shape, derivative-order support, and the stated numerical assumptions for the path you use.

CLASS

AlgebraBudget​

omnibias.core.realization.AlgebraBudgetSource ↗
class AlgebraBudget

Dataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
max_termsdataclass fieldintDefault: 100000See the operation contract and implementation below.
max_degreedataclass fieldintDefault: 64See the operation contract and implementation below.
max_bitsdataclass fieldintDefault: 8192See the operation contract and implementation below.
max_productsdataclass fieldintDefault: 2000000See the operation contract and implementation below.
Executed regression · exact type and budget boundaries

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_exact_type_and_budget_boundaries():
    with pytest.raises(TypeError):
        SparsePolynomial(1, {(1,): 0.1})
    with pytest.raises(TypeError):
        PolynomialNetworkSpec((1, 1, 1), ((False,),))
    with pytest.raises(AlgebraBudgetExceeded):
        compile_coefficient_map(
            PolynomialNetworkSpec.monomial((2, 3, 1)), budget=AlgebraBudget(max_terms=3)
        )
    with pytest.raises(AlgebraBudgetExceeded):
        compile_coefficient_map(
            PolynomialNetworkSpec.monomial((1, 1, 1), 5), budget=AlgebraBudget(max_degree=2)
        )
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_exact_type_and_budget_boundaries" -q

Fields & methods

max_termsfield
max_terms: int = 100000

Declared int field on AlgebraBudget. Default expression: 100000.

View source ↗
max_degreefield
max_degree: int = 64

Declared int field on AlgebraBudget. Default expression: 64.

View source ↗
max_bitsfield
max_bits: int = 8192

Declared int field on AlgebraBudget. Default expression: 8192.

View source ↗
max_productsfield
max_products: int = 2000000

Declared int field on AlgebraBudget. Default expression: 2000000.

View source ↗
__post_init__method
__post_init__(self) -> None

See the class contract above and the exact method implementation below.

Returns: None

Validation & failure cases
  • When any((type(v) is not int or v < 1 for v in values)), raises ValueError('algebra budgets must be positive').
Executed regression · exact type and budget boundaries

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_exact_type_and_budget_boundaries():
    with pytest.raises(TypeError):
        SparsePolynomial(1, {(1,): 0.1})
    with pytest.raises(TypeError):
        PolynomialNetworkSpec((1, 1, 1), ((False,),))
    with pytest.raises(AlgebraBudgetExceeded):
        compile_coefficient_map(
            PolynomialNetworkSpec.monomial((2, 3, 1)), budget=AlgebraBudget(max_terms=3)
        )
    with pytest.raises(AlgebraBudgetExceeded):
        compile_coefficient_map(
            PolynomialNetworkSpec.monomial((1, 1, 1), 5), budget=AlgebraBudget(max_degree=2)
        )
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_exact_type_and_budget_boundaries" -q
Method implementation
    def __post_init__(self) -> None:
        values = (self.max_terms, self.max_degree, self.max_bits, self.max_products)
        if any(type(v) is not int or v < 1 for v in values):
            raise ValueError("algebra budgets must be positive")
View source ↗
Read the implementation
class AlgebraBudget:
    max_terms: int = 100_000
    max_degree: int = 64
    max_bits: int = 8192
    max_products: int = 2_000_000

    def __post_init__(self) -> None:
        values = (self.max_terms, self.max_degree, self.max_bits, self.max_products)
        if any(type(v) is not int or v < 1 for v in values):
            raise ValueError("algebra budgets must be positive")
Other public import paths
  • omnibias.core.realization.AlgebraBudget
  • omnibias.core.realization.polynomial.AlgebraBudget
CLASS

AlgebraBudgetExceeded​

omnibias.core.realization.AlgebraBudgetExceededSource ↗
class AlgebraBudgetExceeded(RuntimeError)

An exact computation stopped; this is not mathematical exclusion.

Regression example · exact type and budget boundaries

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_exact_type_and_budget_boundaries():
    with pytest.raises(TypeError):
        SparsePolynomial(1, {(1,): 0.1})
    with pytest.raises(TypeError):
        PolynomialNetworkSpec((1, 1, 1), ((False,),))
    with pytest.raises(AlgebraBudgetExceeded):
        compile_coefficient_map(
            PolynomialNetworkSpec.monomial((2, 3, 1)), budget=AlgebraBudget(max_terms=3)
        )
    with pytest.raises(AlgebraBudgetExceeded):
        compile_coefficient_map(
            PolynomialNetworkSpec.monomial((1, 1, 1), 5), budget=AlgebraBudget(max_degree=2)
        )
python -m pytest packages/omnibias-core/tests/test_realization_algebra.py -k test_exact_type_and_budget_boundaries -q
Read the implementation
class AlgebraBudgetExceeded(RuntimeError):
    """An exact computation stopped; this is not mathematical exclusion."""
Other public import paths
  • omnibias.core.realization.AlgebraBudgetExceeded
  • omnibias.core.realization.polynomial.AlgebraBudgetExceeded
CONSTANT

MultiIndex​

omnibias.core.realization.polynomial.MultiIndexSource ↗
MultiIndex: TypeAlias = tuple[int, ...]

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
MultiIndex: TypeAlias = tuple[int, ...]
CLASS

PolynomialNetworkSpec​

omnibias.core.realization.PolynomialNetworkSpecSource ↗
class PolynomialNetworkSpec

Dataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.

Row-major weights, followed by biases, for each layer in order.

activations[l][k] is the coefficient of z**k in hidden layer l. The last layer is affine. For homogeneous networks set biases=False.

Parameters

NameType & defaultContract
dimsdataclass fieldtuple[int, ...]RequiredSee the operation contract and implementation below.
activationsdataclass fieldtuple[tuple[Rational, ...], ...]RequiredSee the operation contract and implementation below.
biasesdataclass fieldboolDefault: TrueSee the operation contract and implementation below.
Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Regression example · binary two output complex closure has full ambient dimension

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_binary_two_output_complex_closure_has_full_ambient_dimension():
    # Full Jacobian rank six independently anchors the full-space ED endpoint.
    source = compile_coefficient_map(PolynomialNetworkSpec.monomial((2, 2, 2)))
    report = certify_generic_rank(source.polynomials, (1, 0, 0, 1, 1, 0, 0, 1))
    assert len(source.polynomials) == 6
    assert report.complete and report.lower == report.upper == 6
python -m pytest packages/omnibias-core/tests/test_realization_algebra.py -k test_binary_two_output_complex_closure_has_full_ambient_dimension -q

Fields & methods

dimsfield
dims: tuple[int, ...]

Declared tuple[int, ...] field on PolynomialNetworkSpec. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
activationsfield
activations: tuple[tuple[Rational, ...], ...]

Declared tuple[tuple[Rational, ...], ...] field on PolynomialNetworkSpec. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
biasesfield
biases: bool = True

Declared bool field on PolynomialNetworkSpec. Default expression: True.

View source ↗
__post_init__method
__post_init__(self) -> None

See the class contract above and the exact method implementation below.

Returns: None

Validation & failure cases
  • When type(self.biases) is not bool, raises TypeError('biases must be a boolean').
  • When len(self.dims) < 2 or any((isinstance(d, bool) or not isinstance(d, int) or d < 1 for d in self.dims)), raises ValueError('network dimensions must be positive integers').
  • When len(self.activations) != len(self.dims) - 2 or any((not a for a in self.activations)), raises ValueError('one nonempty coefficient tuple per hidden layer is required').
Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Method implementation
    def __post_init__(self) -> None:
        if type(self.biases) is not bool:
            raise TypeError("biases must be a boolean")
        if len(self.dims) < 2 or any(
            isinstance(d, bool) or not isinstance(d, int) or d < 1 for d in self.dims
        ):
            raise ValueError("network dimensions must be positive integers")
        if len(self.activations) != len(self.dims) - 2 or any(not a for a in self.activations):
            raise ValueError("one nonempty coefficient tuple per hidden layer is required")
        for a in self.activations:
            for c in a:
                rational(c)
View source ↗
n_paramsproperty
n_params(self) -> int

See the class contract above and the exact method implementation below.

Returns: int

Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Method implementation
    def n_params(self) -> int:
        return sum(
            m * n + (m if self.biases else 0)
            for n, m in zip(self.dims[:-1], self.dims[1:], strict=True)
        )
View source ↗
monomialmethod
monomial(cls, dims: Sequence[int], degree: int=2, *, biases: bool=False) -> PolynomialNetworkSpec

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
dimspositional-or-keywordSequence[int]RequiredSee the operation contract and implementation below.
degreepositional-or-keywordintDefault: 2See the operation contract and implementation below.
biaseskeyword-onlyboolDefault: FalseSee the operation contract and implementation below.

Returns: PolynomialNetworkSpec

Validation & failure cases
  • When type(degree) is not int or degree < 1, raises ValueError('activation degree must be positive').
Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Method implementation
    def monomial(
        cls, dims: Sequence[int], degree: int = 2, *, biases: bool = False
    ) -> PolynomialNetworkSpec:
        if type(degree) is not int or degree < 1:
            raise ValueError("activation degree must be positive")
        return cls(tuple(dims), ((0,) * degree + (1,),) * (len(dims) - 2), biases)
View source ↗
to_payloadmethod
to_payload(self) -> dict[str, object]

See the class contract above and the exact method implementation below.

Returns: dict[str, object]

Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Method implementation
    def to_payload(self) -> dict[str, object]:
        return {
            "dims": list(self.dims),
            "biases": self.biases,
            "activations": [
                [[rational(c).numerator, rational(c).denominator] for c in a]
                for a in self.activations
            ],
        }
View source ↗
Read the implementation
class PolynomialNetworkSpec:
    """Row-major weights, followed by biases, for each layer in order.

    ``activations[l][k]`` is the coefficient of ``z**k`` in hidden layer l.
    The last layer is affine. For homogeneous networks set ``biases=False``.
    """

    dims: tuple[int, ...]
    activations: tuple[tuple[Rational, ...], ...]
    biases: bool = True

    def __post_init__(self) -> None:
        if type(self.biases) is not bool:
            raise TypeError("biases must be a boolean")
        if len(self.dims) < 2 or any(
            isinstance(d, bool) or not isinstance(d, int) or d < 1 for d in self.dims
        ):
            raise ValueError("network dimensions must be positive integers")
        if len(self.activations) != len(self.dims) - 2 or any(not a for a in self.activations):
            raise ValueError("one nonempty coefficient tuple per hidden layer is required")
        for a in self.activations:
            for c in a:
                rational(c)

    @property
    def n_params(self) -> int:
        return sum(
            m * n + (m if self.biases else 0)
            for n, m in zip(self.dims[:-1], self.dims[1:], strict=True)
        )

    @classmethod
    def monomial(
        cls, dims: Sequence[int], degree: int = 2, *, biases: bool = False
    ) -> PolynomialNetworkSpec:
        if type(degree) is not int or degree < 1:
            raise ValueError("activation degree must be positive")
        return cls(tuple(dims), ((0,) * degree + (1,),) * (len(dims) - 2), biases)

    def to_payload(self) -> dict[str, object]:
        return {
            "dims": list(self.dims),
            "biases": self.biases,
            "activations": [
                [[rational(c).numerator, rational(c).denominator] for c in a]
                for a in self.activations
            ],
        }
Other public import paths
  • omnibias.core.realization.PolynomialNetworkSpec
  • omnibias.core.realization.polynomial.PolynomialNetworkSpec
CLASS

PolynomialRealizationMap​

omnibias.core.realization.PolynomialRealizationMapSource ↗
class PolynomialRealizationMap

Dataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
specdataclass fieldPolynomialNetworkSpecRequiredSee the operation contract and implementation below.
input_indicesdataclass fieldtuple[MultiIndex, ...]RequiredSee the operation contract and implementation below.
outputsdataclass fieldtuple[tuple[SparsePolynomial, ...], ...]RequiredSee the operation contract and implementation below.
Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q

Fields & methods

specfield
spec: PolynomialNetworkSpec

Declared PolynomialNetworkSpec field on PolynomialRealizationMap. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
input_indicesfield
input_indices: tuple[MultiIndex, ...]

Declared tuple[MultiIndex, ...] field on PolynomialRealizationMap. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
outputsfield
outputs: tuple[tuple[SparsePolynomial, ...], ...]

Declared tuple[tuple[SparsePolynomial, ...], ...] field on PolynomialRealizationMap. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
polynomialsproperty
polynomials(self) -> tuple[SparsePolynomial, ...]

See the class contract above and the exact method implementation below.

Returns: tuple[SparsePolynomial, ...]

Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Method implementation
    def polynomials(self) -> tuple[SparsePolynomial, ...]:
        return tuple(p for row in self.outputs for p in row)
View source ↗
fingerprintproperty
fingerprint(self) -> str

See the class contract above and the exact method implementation below.

Returns: str

Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Method implementation
    def fingerprint(self) -> str:
        body = {
            "spec": self.spec.to_payload(),
            "indices": self.input_indices,
            "map": [p.to_payload() for p in self.polynomials],
        }
        return hashlib.sha256(
            json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
        ).hexdigest()
View source ↗
evaluatemethod
evaluate(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
parameterspositional-or-keywordSequence[Rational]RequiredSee the operation contract and implementation below.

Returns: tuple[tuple[Fraction, ...], ...]

Executed regression · compiler matches independent dense rational forward

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_compiler_matches_independent_dense_rational_forward(spec):
    source = compile_coefficient_map(spec)
    rng = random.Random(842)
    for _ in range(8):
        theta = tuple(Q(rng.randrange(-3, 4), rng.randrange(1, 4)) for _ in range(spec.n_params))
        x = tuple(Q(rng.randrange(-3, 4), 3) for _ in range(spec.dims[0]))
        coeffs = source.evaluate(theta)
        actual = tuple(
            sum(c * _monomial(x, idx) for c, idx in zip(row, source.input_indices, strict=True))
            for row in coeffs
        )
        assert actual == _forward(spec, theta, x)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_compiler_matches_independent_dense_rational_forward[spec0]" -q
Method implementation
    def evaluate(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]:
        return tuple(tuple(p.evaluate(parameters) for p in row) for row in self.outputs)
View source ↗
jacobianmethod
jacobian(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
parameterspositional-or-keywordSequence[Rational]RequiredSee the operation contract and implementation below.

Returns: tuple[tuple[Fraction, ...], ...]

Method implementation
    def jacobian(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]:
        return tuple(
            tuple(p.derivative(i).evaluate(parameters) for i in range(self.spec.n_params))
            for p in self.polynomials
        )
View source ↗
Read the implementation
class PolynomialRealizationMap:
    spec: PolynomialNetworkSpec
    input_indices: tuple[MultiIndex, ...]
    outputs: tuple[tuple[SparsePolynomial, ...], ...]

    @property
    def polynomials(self) -> tuple[SparsePolynomial, ...]:
        return tuple(p for row in self.outputs for p in row)

    @property
    def fingerprint(self) -> str:
        body = {
            "spec": self.spec.to_payload(),
            "indices": self.input_indices,
            "map": [p.to_payload() for p in self.polynomials],
        }
        return hashlib.sha256(
            json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
        ).hexdigest()

    def evaluate(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]:
        return tuple(tuple(p.evaluate(parameters) for p in row) for row in self.outputs)

    def jacobian(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]:
        return tuple(
            tuple(p.derivative(i).evaluate(parameters) for i in range(self.spec.n_params))
            for p in self.polynomials
        )
Other public import paths
  • omnibias.core.realization.PolynomialRealizationMap
  • omnibias.core.realization.polynomial.PolynomialRealizationMap
CONSTANT

Rational​

omnibias.core.realization.polynomial.RationalSource ↗
Rational: TypeAlias = int | Fraction

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
Rational: TypeAlias = int | Fraction
CLASS

SparsePolynomial​

omnibias.core.realization.SparsePolynomialSource ↗
class SparsePolynomial

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
nvarspositional-or-keywordintRequiredSee the operation contract and implementation below.
termspositional-or-keywordMapping[MultiIndex, Rational] | NoneDefault: NoneSee the operation contract and implementation below.
budgetkeyword-onlyAlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGETSee the operation contract and implementation below.
Executed regression · actual kernel build when toolchain available

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_actual_kernel_build_when_toolchain_available(certificate):
    from omnibias.core.proof.lean_check import check_certificate, lean_check_available

    if not lean_check_available():
        pytest.skip("Lean toolchain unavailable")
    assert check_certificate(certificate).verified
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_actual_kernel_build_when_toolchain_available[certificate0]" -q
Regression example · signed root regimes against atan atanh

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_signed_root_regimes_against_atan_atanh(delta, value, p, endpoint):
    with mp.workdps(100):
        result = signed_root_primitive(delta, value, delta_order=p, endpoint_order=endpoint)
        contains(result, root_reference(delta, value, p, endpoint))
python -m pytest packages/omnibias-core/tests/verified/test_asymptotic_jet.py -k test_signed_root_regimes_against_atan_atanh -q

Fields & methods

nvarsfield
nvars: int

Declared int field on SparsePolynomial. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
termsfield
terms: tuple[tuple[MultiIndex, Fraction], ...]

Declared tuple[tuple[MultiIndex, Fraction], ...] field on SparsePolynomial. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
budgetfield
budget: AlgebraBudget

Declared AlgebraBudget field on SparsePolynomial. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
__init__method
__init__(self, nvars: int, terms: Mapping[MultiIndex, Rational] | None=None, *, budget: AlgebraBudget=DEFAULT_ALGEBRA_BUDGET) -> None

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
nvarspositional-or-keywordintRequiredSee the operation contract and implementation below.
termspositional-or-keywordMapping[MultiIndex, Rational] | NoneDefault: NoneSee the operation contract and implementation below.
budgetkeyword-onlyAlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGETSee the operation contract and implementation below.

Returns: None

Validation & failure cases
  • When type(nvars) is not int or nvars < 0, raises ValueError('nvars must be nonnegative').
  • When len(idx) != nvars or any((isinstance(i, bool) or not isinstance(i, int) or i < 0 for i in idx)), raises ValueError('invalid polynomial multi-index').
  • When sum(idx) > budget.max_degree, raises AlgebraBudgetExceeded('polynomial degree budget exceeded').
  • When max(abs(c.numerator).bit_length(), c.denominator.bit_length()) > budget.max_bits, raises AlgebraBudgetExceeded('rational coefficient bit budget exceeded').
  • When len(clean) > budget.max_terms, raises AlgebraBudgetExceeded('polynomial term budget exceeded').
Executed regression · actual kernel build when toolchain available

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_actual_kernel_build_when_toolchain_available(certificate):
    from omnibias.core.proof.lean_check import check_certificate, lean_check_available

    if not lean_check_available():
        pytest.skip("Lean toolchain unavailable")
    assert check_certificate(certificate).verified
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_actual_kernel_build_when_toolchain_available[certificate0]" -q
Method implementation
    def __init__(
        self,
        nvars: int,
        terms: Mapping[MultiIndex, Rational] | None = None,
        *,
        budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET,
    ) -> None:
        if type(nvars) is not int or nvars < 0:
            raise ValueError("nvars must be nonnegative")
        clean: list[tuple[MultiIndex, Fraction]] = []
        for idx, coeff in (terms or {}).items():
            if len(idx) != nvars or any(
                isinstance(i, bool) or not isinstance(i, int) or i < 0 for i in idx
            ):
                raise ValueError("invalid polynomial multi-index")
            c = rational(coeff)
            if not c:
                continue
            if sum(idx) > budget.max_degree:
                raise AlgebraBudgetExceeded("polynomial degree budget exceeded")
            if max(abs(c.numerator).bit_length(), c.denominator.bit_length()) > budget.max_bits:
                raise AlgebraBudgetExceeded("rational coefficient bit budget exceeded")
            clean.append((tuple(idx), c))
        if len(clean) > budget.max_terms:
            raise AlgebraBudgetExceeded("polynomial term budget exceeded")
        object.__setattr__(self, "nvars", nvars)
        object.__setattr__(
            self, "terms", tuple(sorted(clean, key=lambda item: (sum(item[0]), item[0])))
        )
        object.__setattr__(self, "budget", budget)
View source ↗
constantmethod
constant(cls, nvars: int, value: Rational, *, budget: AlgebraBudget=DEFAULT_ALGEBRA_BUDGET) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
nvarspositional-or-keywordintRequiredSee the operation contract and implementation below.
valuepositional-or-keywordRationalRequiredSee the operation contract and implementation below.
budgetkeyword-onlyAlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGETSee the operation contract and implementation below.

Returns: SparsePolynomial

Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def constant(
        cls, nvars: int, value: Rational, *, budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET
    ) -> SparsePolynomial:
        return cls(nvars, {(0,) * nvars: value}, budget=budget)
View source ↗
variablemethod
variable(cls, nvars: int, axis: int, *, budget: AlgebraBudget=DEFAULT_ALGEBRA_BUDGET) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
nvarspositional-or-keywordintRequiredSee the operation contract and implementation below.
axispositional-or-keywordintRequiredSee the operation contract and implementation below.
budgetkeyword-onlyAlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGETSee the operation contract and implementation below.

Returns: SparsePolynomial

Validation & failure cases
  • When not 0 <= axis < nvars, raises ValueError('variable axis out of range').
Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def variable(
        cls, nvars: int, axis: int, *, budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET
    ) -> SparsePolynomial:
        if not 0 <= axis < nvars:
            raise ValueError("variable axis out of range")
        index = tuple(int(i == axis) for i in range(nvars))
        return cls(nvars, {index: 1}, budget=budget)
View source ↗
__add__method
__add__(self, other: SparsePolynomial | Rational) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
otherpositional-or-keywordSparsePolynomial | RationalRequiredSee the operation contract and implementation below.

Returns: SparsePolynomial

Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def __add__(self, other: SparsePolynomial | Rational) -> SparsePolynomial:
        p = self._coerce(other)
        terms = dict(self.terms)
        for i, c in p.terms:
            terms[i] = terms.get(i, Fraction(0)) + c
        return SparsePolynomial(self.nvars, terms, budget=self.budget)
View source ↗
__radd__method
__radd__(self, other: Rational) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
otherpositional-or-keywordRationalRequiredSee the operation contract and implementation below.

Returns: SparsePolynomial

Method implementation
    def __radd__(self, other: Rational) -> SparsePolynomial:
        return self + other
View source ↗
__neg__method
__neg__(self) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Returns: SparsePolynomial

Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def __neg__(self) -> SparsePolynomial:
        return SparsePolynomial(self.nvars, {i: -c for i, c in self.terms}, budget=self.budget)
View source ↗
__sub__method
__sub__(self, other: SparsePolynomial | Rational) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
otherpositional-or-keywordSparsePolynomial | RationalRequiredSee the operation contract and implementation below.

Returns: SparsePolynomial

Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def __sub__(self, other: SparsePolynomial | Rational) -> SparsePolynomial:
        return self + -self._coerce(other)
View source ↗
__mul__method
__mul__(self, other: SparsePolynomial | Rational) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
otherpositional-or-keywordSparsePolynomial | RationalRequiredSee the operation contract and implementation below.

Returns: SparsePolynomial

Validation & failure cases
  • When len(self.terms) * len(p.terms) > self.budget.max_products, raises AlgebraBudgetExceeded('polynomial product budget exceeded').
  • When len(terms) > self.budget.max_terms, raises AlgebraBudgetExceeded('intermediate polynomial term budget exceeded').
Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def __mul__(self, other: SparsePolynomial | Rational) -> SparsePolynomial:
        p = self._coerce(other)
        if len(self.terms) * len(p.terms) > self.budget.max_products:
            raise AlgebraBudgetExceeded("polynomial product budget exceeded")
        terms: dict[MultiIndex, Fraction] = {}
        for i, a in self.terms:
            for j, b in p.terms:
                k = tuple(x + y for x, y in zip(i, j, strict=True))
                terms[k] = terms.get(k, Fraction(0)) + a * b
                if len(terms) > self.budget.max_terms:
                    raise AlgebraBudgetExceeded("intermediate polynomial term budget exceeded")
        return SparsePolynomial(self.nvars, terms, budget=self.budget)
View source ↗
__rmul__method
__rmul__(self, other: Rational) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
otherpositional-or-keywordRationalRequiredSee the operation contract and implementation below.

Returns: SparsePolynomial

Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def __rmul__(self, other: Rational) -> SparsePolynomial:
        return self * other
View source ↗
__pow__method
__pow__(self, exponent: int) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
exponentpositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: SparsePolynomial

Validation & failure cases
  • When isinstance(exponent, bool) or not isinstance(exponent, int) or exponent < 0, raises ValueError('polynomial powers must be nonnegative integers').
Executed regression · moment identity embeds original offsets weights and center

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_moment_identity_embeds_original_offsets_weights_and_center():
    certificate = moment_identity_replay_certificate(
        (1, -1), (2, 3), center=0, expected_moments=(5, -1, Q(5, 2), -Q(1, 6), Q(5, 24))
    )
    assert verify_replay_certificate(certificate)
    assert len(certificate["payload"]["point"]) == 5
    false = deepcopy(certificate)
    false["payload"]["point"][0] = [3, 1]
    assert not verify_replay_certificate(seal_certificate(false))
    with pytest.raises(ValueError):
        moment_identity_replay_certificate((1, -1), (2, 3), center=0, expected_moments=(5, 0))
python -m pytest "packages/omnibias-core/tests/proof/test_realization_algebra_replay.py::test_moment_identity_embeds_original_offsets_weights_and_center" -q
Method implementation
    def __pow__(self, exponent: int) -> SparsePolynomial:
        if isinstance(exponent, bool) or not isinstance(exponent, int) or exponent < 0:
            raise ValueError("polynomial powers must be nonnegative integers")
        result = self.constant(self.nvars, 1, budget=self.budget)
        base = self
        while exponent:
            if exponent & 1:
                result = result * base
            exponent //= 2
            if exponent:
                base = base * base
        return result
View source ↗
derivativemethod
derivative(self, axis: int) -> SparsePolynomial

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
axispositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: SparsePolynomial

Validation & failure cases
  • When not 0 <= axis < self.nvars, raises ValueError('derivative axis out of range').
Executed regression · binary two output complex closure has full ambient dimension

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_binary_two_output_complex_closure_has_full_ambient_dimension():
    # Full Jacobian rank six independently anchors the full-space ED endpoint.
    source = compile_coefficient_map(PolynomialNetworkSpec.monomial((2, 2, 2)))
    report = certify_generic_rank(source.polynomials, (1, 0, 0, 1, 1, 0, 0, 1))
    assert len(source.polynomials) == 6
    assert report.complete and report.lower == report.upper == 6
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_binary_two_output_complex_closure_has_full_ambient_dimension" -q
Method implementation
    def derivative(self, axis: int) -> SparsePolynomial:
        if not 0 <= axis < self.nvars:
            raise ValueError("derivative axis out of range")
        terms = {}
        for idx, c in self.terms:
            if idx[axis]:
                j = list(idx)
                j[axis] -= 1
                terms[tuple(j)] = c * idx[axis]
        return SparsePolynomial(self.nvars, terms, budget=self.budget)
View source ↗
evaluatemethod
evaluate(self, point: Sequence[Rational]) -> Fraction

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
pointpositional-or-keywordSequence[Rational]RequiredSee the operation contract and implementation below.

Returns: Fraction

Validation & failure cases
  • When len(point) != self.nvars, raises ValueError('evaluation point has wrong dimension').
Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def evaluate(self, point: Sequence[Rational]) -> Fraction:
        if len(point) != self.nvars:
            raise ValueError("evaluation point has wrong dimension")
        values = tuple(rational(x) for x in point)
        out = Fraction(0)
        for idx, c in self.terms:
            for x, power in zip(values, idx, strict=True):
                c *= x**power
            out += c
        return out
View source ↗
to_payloadmethod
to_payload(self) -> dict[str, object]

See the class contract above and the exact method implementation below.

Returns: dict[str, object]

Executed regression · resealed rank factor substitution cannot borrow original minor

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_resealed_rank_factor_substitution_cannot_borrow_original_minor():
    certificate = _examples()[2]
    false = deepcopy(certificate)
    false["payload"]["left"][0][0] = [100, 1]
    false = seal_certificate(false)
    assert not verify_replay_certificate(false)
    assert generate_replay_obligation(false) is not None
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -q
Method implementation
    def to_payload(self) -> dict[str, object]:
        return {
            "nvars": self.nvars,
            "terms": [[list(i), [c.numerator, c.denominator]] for i, c in self.terms],
        }
View source ↗
Read the implementation
class SparsePolynomial:
    nvars: int
    terms: tuple[tuple[MultiIndex, Fraction], ...]
    budget: AlgebraBudget

    def __init__(
        self,
        nvars: int,
        terms: Mapping[MultiIndex, Rational] | None = None,
        *,
        budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET,
    ) -> None:
        if type(nvars) is not int or nvars < 0:
            raise ValueError("nvars must be nonnegative")
        clean: list[tuple[MultiIndex, Fraction]] = []
        for idx, coeff in (terms or {}).items():
            if len(idx) != nvars or any(
                isinstance(i, bool) or not isinstance(i, int) or i < 0 for i in idx
            ):
                raise ValueError("invalid polynomial multi-index")
            c = rational(coeff)
            if not c:
                continue
            if sum(idx) > budget.max_degree:
                raise AlgebraBudgetExceeded("polynomial degree budget exceeded")
            if max(abs(c.numerator).bit_length(), c.denominator.bit_length()) > budget.max_bits:
                raise AlgebraBudgetExceeded("rational coefficient bit budget exceeded")
            clean.append((tuple(idx), c))
        if len(clean) > budget.max_terms:
            raise AlgebraBudgetExceeded("polynomial term budget exceeded")
        object.__setattr__(self, "nvars", nvars)
        object.__setattr__(
            self, "terms", tuple(sorted(clean, key=lambda item: (sum(item[0]), item[0])))
        )
        object.__setattr__(self, "budget", budget)

    @classmethod
    def constant(
        cls, nvars: int, value: Rational, *, budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET
    ) -> SparsePolynomial:
        return cls(nvars, {(0,) * nvars: value}, budget=budget)

    @classmethod
    def variable(
        cls, nvars: int, axis: int, *, budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET
    ) -> SparsePolynomial:
        if not 0 <= axis < nvars:
            raise ValueError("variable axis out of range")
        index = tuple(int(i == axis) for i in range(nvars))
        return cls(nvars, {index: 1}, budget=budget)

    def _coerce(self, value: SparsePolynomial | Rational) -> SparsePolynomial:
        p = (
            value
            if isinstance(value, SparsePolynomial)
            else self.constant(self.nvars, value, budget=self.budget)
        )
        if p.nvars != self.nvars:
            raise ValueError("polynomial variable counts differ")
        return p

    def __add__(self, other: SparsePolynomial | Rational) -> SparsePolynomial:
        p = self._coerce(other)
        terms = dict(self.terms)
        for i, c in p.terms:
            terms[i] = terms.get(i, Fraction(0)) + c
        return SparsePolynomial(self.nvars, terms, budget=self.budget)

    def __radd__(self, other: Rational) -> SparsePolynomial:
        return self + other

    def __neg__(self) -> SparsePolynomial:
        return SparsePolynomial(self.nvars, {i: -c for i, c in self.terms}, budget=self.budget)

    def __sub__(self, other: SparsePolynomial | Rational) -> SparsePolynomial:
        return self + -self._coerce(other)

    def __mul__(self, other: SparsePolynomial | Rational) -> SparsePolynomial:
        p = self._coerce(other)
        if len(self.terms) * len(p.terms) > self.budget.max_products:
            raise AlgebraBudgetExceeded("polynomial product budget exceeded")
        terms: dict[MultiIndex, Fraction] = {}
        for i, a in self.terms:
            for j, b in p.terms:
                k = tuple(x + y for x, y in zip(i, j, strict=True))
                terms[k] = terms.get(k, Fraction(0)) + a * b
                if len(terms) > self.budget.max_terms:
                    raise AlgebraBudgetExceeded("intermediate polynomial term budget exceeded")
        return SparsePolynomial(self.nvars, terms, budget=self.budget)

    def __rmul__(self, other: Rational) -> SparsePolynomial:
        return self * other

    def __pow__(self, exponent: int) -> SparsePolynomial:
        if isinstance(exponent, bool) or not isinstance(exponent, int) or exponent < 0:
            raise ValueError("polynomial powers must be nonnegative integers")
        result = self.constant(self.nvars, 1, budget=self.budget)
        base = self
        while exponent:
            if exponent & 1:
                result = result * base
            exponent //= 2
            if exponent:
                base = base * base
        return result

    def derivative(self, axis: int) -> SparsePolynomial:
        if not 0 <= axis < self.nvars:
            raise ValueError("derivative axis out of range")
        terms = {}
        for idx, c in self.terms:
            if idx[axis]:
                j = list(idx)
                j[axis] -= 1
                terms[tuple(j)] = c * idx[axis]
        return SparsePolynomial(self.nvars, terms, budget=self.budget)

    def evaluate(self, point: Sequence[Rational]) -> Fraction:
        if len(point) != self.nvars:
            raise ValueError("evaluation point has wrong dimension")
        values = tuple(rational(x) for x in point)
        out = Fraction(0)
        for idx, c in self.terms:
            for x, power in zip(values, idx, strict=True):
                c *= x**power
            out += c
        return out

    def to_payload(self) -> dict[str, object]:
        return {
            "nvars": self.nvars,
            "terms": [[list(i), [c.numerator, c.denominator]] for i, c in self.terms],
        }
Other public import paths
  • omnibias.core.realization.SparsePolynomial
  • omnibias.core.realization.polynomial.SparsePolynomial
FUNCTION

compile_coefficient_map​

omnibias.core.realization.compile_coefficient_mapSource ↗
compile_coefficient_map(spec: PolynomialNetworkSpec, *, budget: AlgebraBudget=DEFAULT_ALGEBRA_BUDGET) -> PolynomialRealizationMap

Compile a polynomial map in all parameters, collecting all input terms.

The returned index ordering is explicit and includes only input monomials occurring symbolically. Reaching a budget raises AlgebraBudgetExceeded.

Parameters

NameType & defaultContract
specpositional-or-keywordPolynomialNetworkSpecRequiredSee the operation contract and implementation below.
budgetkeyword-onlyAlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGETSee the operation contract and implementation below.
ReturnsPolynomialRealizationMap
Executed regression · linear membership arbitrary depth

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_linear_membership_arbitrary_depth(hidden):
    report = classify_linear([[1, 2, 3], [-1, 2, 0]], hidden)
    assert report.status == "realizable" and report.witness.verify(report.source)
    assert not replace(report.witness, target=tuple(t + 1 for t in report.target)).verify(
        report.source
    )
    assert classify_linear([[1, 0], [0, 1]], (1, 3)).status == "excluded"
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_linear_membership_arbitrary_depth[hidden0]" -q
Regression example · binary two output complex closure has full ambient dimension

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_binary_two_output_complex_closure_has_full_ambient_dimension():
    # Full Jacobian rank six independently anchors the full-space ED endpoint.
    source = compile_coefficient_map(PolynomialNetworkSpec.monomial((2, 2, 2)))
    report = certify_generic_rank(source.polynomials, (1, 0, 0, 1, 1, 0, 0, 1))
    assert len(source.polynomials) == 6
    assert report.complete and report.lower == report.upper == 6
python -m pytest packages/omnibias-core/tests/test_realization_algebra.py -k test_binary_two_output_complex_closure_has_full_ambient_dimension -q
Read the implementation
def compile_coefficient_map(
    spec: PolynomialNetworkSpec, *, budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET
) -> PolynomialRealizationMap:
    """Compile a polynomial map in all parameters, collecting all input terms.

    The returned index ordering is explicit and includes only input monomials
    occurring symbolically. Reaching a budget raises ``AlgebraBudgetExceeded``.
    """
    p = spec.n_params
    nvars = p + spec.dims[0]
    variables = [SparsePolynomial.variable(nvars, i, budget=budget) for i in range(p)]
    values = [SparsePolynomial.variable(nvars, p + i, budget=budget) for i in range(spec.dims[0])]
    offset = 0
    for layer, (n_in, n_out) in enumerate(zip(spec.dims[:-1], spec.dims[1:], strict=True)):
        weights = [variables[offset + i * n_in : offset + (i + 1) * n_in] for i in range(n_out)]
        offset += n_in * n_out
        bias = (
            variables[offset : offset + n_out]
            if spec.biases
            else [SparsePolynomial.constant(nvars, 0, budget=budget)] * n_out
        )
        offset += n_out if spec.biases else 0
        result = []
        for row, b in zip(weights, bias, strict=True):
            z = b
            for w, x in zip(row, values, strict=True):
                z = z + w * x
            if layer < len(spec.activations):
                a = SparsePolynomial.constant(nvars, 0, budget=budget)
                for coeff in reversed(spec.activations[layer]):
                    a = a * z + coeff
                z = a
            result.append(z)
        values = result
    indices = tuple(
        sorted({idx[p:] for value in values for idx, _ in value.terms}, key=lambda i: (sum(i), i))
    )
    # A zero activation can yield a zero map with no terms. Keep the constant
    # slot so even this map has an explicit, nonempty coefficient target.
    if not indices:
        indices = ((0,) * spec.dims[0],)
    rows = []
    for value in values:
        collected: dict[MultiIndex, dict[MultiIndex, Fraction]] = {i: {} for i in indices}
        for idx, c in value.terms:
            collected[idx[p:]][idx[:p]] = c
        rows.append(tuple(SparsePolynomial(p, collected[i], budget=budget) for i in indices))
    return PolynomialRealizationMap(spec, indices, tuple(rows))
Other public import paths
  • omnibias.core.realization.compile_coefficient_map
  • omnibias.core.realization.polynomial.compile_coefficient_map
FUNCTION

rational​

omnibias.core.realization.polynomial.rationalSource ↗
rational(value: Rational) -> Fraction

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
valuepositional-or-keywordRationalRequiredSee the operation contract and implementation below.
ReturnsFraction
Explicit validation & failure cases
  • When isinstance(value, bool) or not isinstance(value, (int, Fraction)), raises TypeError('exact coefficients require int or Fraction, not floats').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · actual kernel build when toolchain available

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_actual_kernel_build_when_toolchain_available(certificate):
    from omnibias.core.proof.lean_check import check_certificate, lean_check_available

    if not lean_check_available():
        pytest.skip("Lean toolchain unavailable")
    assert check_certificate(certificate).verified
python -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_actual_kernel_build_when_toolchain_available[certificate0]" -q
Read the implementation
def rational(value: Rational) -> Fraction:
    if isinstance(value, bool) or not isinstance(value, (int, Fraction)):
        raise TypeError("exact coefficients require int or Fraction, not floats")
    return Fraction(value)