omnibias.core.realization.polynomial
Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.
import omnibias.core.realization.polynomialModule 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.
AlgebraBudget
omnibias.core.realization.AlgebraBudgetSource ↗class AlgebraBudgetDataclass 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
| Name | Type & default | Contract |
|---|---|---|
max_termsdataclass field | intDefault: 100000 | See the operation contract and implementation below. |
max_degreedataclass field | intDefault: 64 | See the operation contract and implementation below. |
max_bitsdataclass field | intDefault: 8192 | See the operation contract and implementation below. |
max_productsdataclass field | intDefault: 2000000 | See 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" -qFields & methods
max_termsfield
max_terms: int = 100000Declared int field on AlgebraBudget. Default expression: 100000.
max_degreefield
max_degree: int = 64Declared int field on AlgebraBudget. Default expression: 64.
max_bitsfield
max_bits: int = 8192Declared int field on AlgebraBudget. Default expression: 8192.
max_productsfield
max_products: int = 2000000Declared int field on AlgebraBudget. Default expression: 2000000.
__post_init__method
__post_init__(self) -> NoneSee 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)), raisesValueError('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" -qMethod 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")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.AlgebraBudgetomnibias.core.realization.polynomial.AlgebraBudget
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 -qRead the implementation
class AlgebraBudgetExceeded(RuntimeError):
"""An exact computation stopped; this is not mathematical exclusion."""Other public import paths
omnibias.core.realization.AlgebraBudgetExceededomnibias.core.realization.polynomial.AlgebraBudgetExceeded
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, ...]PolynomialNetworkSpec
omnibias.core.realization.PolynomialNetworkSpecSource ↗class PolynomialNetworkSpecDataclass 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
| Name | Type & default | Contract |
|---|---|---|
dimsdataclass field | tuple[int, ...]Required | See the operation contract and implementation below. |
activationsdataclass field | tuple[tuple[Rational, ...], ...]Required | See the operation contract and implementation below. |
biasesdataclass field | boolDefault: True | See 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]" -qRegression 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 == 6python -m pytest packages/omnibias-core/tests/test_realization_algebra.py -k test_binary_two_output_complex_closure_has_full_ambient_dimension -qFields & 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 = TrueDeclared bool field on PolynomialNetworkSpec. Default expression: True.
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
type(self.biases) is not bool, raisesTypeError('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)), raisesValueError('network dimensions must be positive integers'). - When
len(self.activations) != len(self.dims) - 2 or any((not a for a in self.activations)), raisesValueError('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]" -qMethod 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)n_paramsproperty
n_params(self) -> intSee 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]" -qMethod 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)
)monomialmethod
monomial(cls, dims: Sequence[int], degree: int=2, *, biases: bool=False) -> PolynomialNetworkSpecSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
dimspositional-or-keyword | Sequence[int]Required | See the operation contract and implementation below. |
degreepositional-or-keyword | intDefault: 2 | See the operation contract and implementation below. |
biaseskeyword-only | boolDefault: False | See the operation contract and implementation below. |
Returns: PolynomialNetworkSpec
Validation & failure cases
- When
type(degree) is not int or degree < 1, raisesValueError('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]" -qMethod 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)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]" -qMethod 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
],
}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.PolynomialNetworkSpecomnibias.core.realization.polynomial.PolynomialNetworkSpec
PolynomialRealizationMap
omnibias.core.realization.PolynomialRealizationMapSource ↗class PolynomialRealizationMapDataclass 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
| Name | Type & default | Contract |
|---|---|---|
specdataclass field | PolynomialNetworkSpecRequired | See the operation contract and implementation below. |
input_indicesdataclass field | tuple[MultiIndex, ...]Required | See the operation contract and implementation below. |
outputsdataclass field | tuple[tuple[SparsePolynomial, ...], ...]Required | See 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]" -qFields & methods
specfield
spec: PolynomialNetworkSpecDeclared 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]" -qMethod implementation
def polynomials(self) -> tuple[SparsePolynomial, ...]:
return tuple(p for row in self.outputs for p in row)fingerprintproperty
fingerprint(self) -> strSee 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]" -qMethod 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()evaluatemethod
evaluate(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]See the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
parameterspositional-or-keyword | Sequence[Rational]Required | See 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]" -qMethod 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)jacobianmethod
jacobian(self, parameters: Sequence[Rational]) -> tuple[tuple[Fraction, ...], ...]See the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
parameterspositional-or-keyword | Sequence[Rational]Required | See 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
)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.PolynomialRealizationMapomnibias.core.realization.polynomial.PolynomialRealizationMap
Rational
omnibias.core.realization.polynomial.RationalSource ↗Rational: TypeAlias = int | FractionThis 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 | FractionSparsePolynomial
omnibias.core.realization.SparsePolynomialSource ↗class SparsePolynomialThe module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
nvarspositional-or-keyword | intRequired | See the operation contract and implementation below. |
termspositional-or-keyword | Mapping[MultiIndex, Rational] | NoneDefault: None | See the operation contract and implementation below. |
budgetkeyword-only | AlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGET | See 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).verifiedpython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_actual_kernel_build_when_toolchain_available[certificate0]" -qRegression 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 -qFields & methods
nvarsfield
nvars: intDeclared 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: AlgebraBudgetDeclared 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) -> NoneSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
nvarspositional-or-keyword | intRequired | See the operation contract and implementation below. |
termspositional-or-keyword | Mapping[MultiIndex, Rational] | NoneDefault: None | See the operation contract and implementation below. |
budgetkeyword-only | AlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGET | See the operation contract and implementation below. |
Returns: None
Validation & failure cases
- When
type(nvars) is not int or nvars < 0, raisesValueError('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)), raisesValueError('invalid polynomial multi-index'). - When
sum(idx) > budget.max_degree, raisesAlgebraBudgetExceeded('polynomial degree budget exceeded'). - When
max(abs(c.numerator).bit_length(), c.denominator.bit_length()) > budget.max_bits, raisesAlgebraBudgetExceeded('rational coefficient bit budget exceeded'). - When
len(clean) > budget.max_terms, raisesAlgebraBudgetExceeded('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).verifiedpython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_actual_kernel_build_when_toolchain_available[certificate0]" -qMethod 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)constantmethod
constant(cls, nvars: int, value: Rational, *, budget: AlgebraBudget=DEFAULT_ALGEBRA_BUDGET) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
nvarspositional-or-keyword | intRequired | See the operation contract and implementation below. |
valuepositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
budgetkeyword-only | AlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGET | See 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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod implementation
def constant(
cls, nvars: int, value: Rational, *, budget: AlgebraBudget = DEFAULT_ALGEBRA_BUDGET
) -> SparsePolynomial:
return cls(nvars, {(0,) * nvars: value}, budget=budget)variablemethod
variable(cls, nvars: int, axis: int, *, budget: AlgebraBudget=DEFAULT_ALGEBRA_BUDGET) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
nvarspositional-or-keyword | intRequired | See the operation contract and implementation below. |
axispositional-or-keyword | intRequired | See the operation contract and implementation below. |
budgetkeyword-only | AlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGET | See the operation contract and implementation below. |
Returns: SparsePolynomial
Validation & failure cases
- When
not 0 <= axis < nvars, raisesValueError('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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod 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)__add__method
__add__(self, other: SparsePolynomial | Rational) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | SparsePolynomial | RationalRequired | See 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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod 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)__radd__method
__radd__(self, other: Rational) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
Returns: SparsePolynomial
Method implementation
def __radd__(self, other: Rational) -> SparsePolynomial:
return self + other__neg__method
__neg__(self) -> SparsePolynomialSee 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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod implementation
def __neg__(self) -> SparsePolynomial:
return SparsePolynomial(self.nvars, {i: -c for i, c in self.terms}, budget=self.budget)__sub__method
__sub__(self, other: SparsePolynomial | Rational) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | SparsePolynomial | RationalRequired | See 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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod implementation
def __sub__(self, other: SparsePolynomial | Rational) -> SparsePolynomial:
return self + -self._coerce(other)__mul__method
__mul__(self, other: SparsePolynomial | Rational) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | SparsePolynomial | RationalRequired | See the operation contract and implementation below. |
Returns: SparsePolynomial
Validation & failure cases
- When
len(self.terms) * len(p.terms) > self.budget.max_products, raisesAlgebraBudgetExceeded('polynomial product budget exceeded'). - When
len(terms) > self.budget.max_terms, raisesAlgebraBudgetExceeded('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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod 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)__rmul__method
__rmul__(self, other: Rational) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | RationalRequired | See 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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod implementation
def __rmul__(self, other: Rational) -> SparsePolynomial:
return self * other__pow__method
__pow__(self, exponent: int) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
exponentpositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: SparsePolynomial
Validation & failure cases
- When
isinstance(exponent, bool) or not isinstance(exponent, int) or exponent < 0, raisesValueError('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" -qMethod 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 resultderivativemethod
derivative(self, axis: int) -> SparsePolynomialSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
axispositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: SparsePolynomial
Validation & failure cases
- When
not 0 <= axis < self.nvars, raisesValueError('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 == 6python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_binary_two_output_complex_closure_has_full_ambient_dimension" -qMethod 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)evaluatemethod
evaluate(self, point: Sequence[Rational]) -> FractionSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
pointpositional-or-keyword | Sequence[Rational]Required | See the operation contract and implementation below. |
Returns: Fraction
Validation & failure cases
- When
len(point) != self.nvars, raisesValueError('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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod 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 outto_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 Nonepython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_resealed_rank_factor_substitution_cannot_borrow_original_minor" -qMethod 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],
}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.SparsePolynomialomnibias.core.realization.polynomial.SparsePolynomial
compile_coefficient_map
omnibias.core.realization.compile_coefficient_mapSource ↗compile_coefficient_map(spec: PolynomialNetworkSpec, *, budget: AlgebraBudget=DEFAULT_ALGEBRA_BUDGET) -> PolynomialRealizationMapCompile 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
| Name | Type & default | Contract |
|---|---|---|
specpositional-or-keyword | PolynomialNetworkSpecRequired | See the operation contract and implementation below. |
budgetkeyword-only | AlgebraBudgetDefault: DEFAULT_ALGEBRA_BUDGET | See the operation contract and implementation below. |
PolynomialRealizationMapExecuted 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]" -qRegression 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 == 6python -m pytest packages/omnibias-core/tests/test_realization_algebra.py -k test_binary_two_output_complex_closure_has_full_ambient_dimension -qRead 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_mapomnibias.core.realization.polynomial.compile_coefficient_map
rational
omnibias.core.realization.polynomial.rationalSource ↗rational(value: Rational) -> FractionThe module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuepositional-or-keyword | RationalRequired | See the operation contract and implementation below. |
FractionExplicit validation & failure cases
- When
isinstance(value, bool) or not isinstance(value, (int, Fraction)), raisesTypeError('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).verifiedpython -m pytest "packages/omnibias-core/tests/proof/test_realization_replay.py::test_actual_kernel_build_when_toolchain_available[certificate0]" -qRead 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)