Skip to main content

omnibias.core.realization.algebraic

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.algebraic
Module contract & mathematical conventions

Portable real algebraic values with exact Sturm root isolation.

The primitive polynomial need not be irreducible. Equality/sign refer to its one root in the isolating interval. Division requires a unit modulo that polynomial; callers can refine a reducible primitive representation first.

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

AlgebraicNumber​

omnibias.core.realization.AlgebraicNumberSource ↗
class AlgebraicNumber

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
fielddataclass fieldRealAlgebraicFieldRequiredSee the operation contract and implementation below.
coefficientsdataclass fieldUPolyRequiredSee the operation contract and implementation below.
Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q

Fields & methods

fieldfield
field: RealAlgebraicField

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

View source ↗
coefficientsfield
coefficients: UPoly

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

View source ↗
__post_init__method
__post_init__(self) -> None

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

Returns: None

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __post_init__(self) -> None:
        object.__setattr__(
            self, "coefficients", divide(trim(self.coefficients), trim(self.field.polynomial))[1]
        )
View source ↗
__add__method
__add__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __add__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        return self.field.number(add(self.coefficients, self._coerce(other).coefficients))
View source ↗
__radd__method
__radd__(self, other: Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

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

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __neg__(self) -> AlgebraicNumber:
        return self.field.number(scale(self.coefficients, -1))
View source ↗
__sub__method
__sub__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __sub__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        return self + -self._coerce(other)
View source ↗
__rsub__method
__rsub__(self, other: Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Method implementation
    def __rsub__(self, other: Rational) -> AlgebraicNumber:
        return -self + other
View source ↗
__mul__method
__mul__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __mul__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        return self.field.number(multiply(self.coefficients, self._coerce(other).coefficients))
View source ↗
__rmul__method
__rmul__(self, other: Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __rmul__(self, other: Rational) -> AlgebraicNumber:
        return self * other
View source ↗
inversemethod
inverse(self) -> AlgebraicNumber

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

Returns: AlgebraicNumber

Validation & failure cases
  • When len(a) != 1, raises ZeroDivisionError('nonunit denominator; refine the primitive polynomial if necessary').
Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def inverse(self) -> AlgebraicNumber:
        a, b = trim(self.field.polynomial), self.coefficients
        u: UPoly = ()
        v: UPoly = (Fraction(1),)
        while b:
            q, rem = divide(a, b)
            a, b, u, v = b, rem, v, add(u, scale(multiply(q, v), -1))
        if len(a) != 1:
            raise ZeroDivisionError(
                "nonunit denominator; refine the primitive polynomial if necessary"
            )
        return self.field.number(scale(u, 1 / a[0]))
View source ↗
__truediv__method
__truediv__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __truediv__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        return self * self._coerce(other).inverse()
View source ↗
__pow__method
__pow__(self, n: int) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Validation & failure cases
  • When type(n) is not int, raises TypeError('algebraic powers must be integers').
Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def __pow__(self, n: int) -> AlgebraicNumber:
        if type(n) is not int:
            raise TypeError("algebraic powers must be integers")
        if n < 0:
            return self.inverse() ** -n
        out, base = self.field.constant(1), self
        while n:
            if n & 1:
                out = out * base
            n //= 2
            if n:
                base = base * base
        return out
View source ↗
is_zeromethod
is_zero(self) -> bool

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

Returns: bool

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def is_zero(self) -> bool:
        if not self.coefficients:
            return True
        common = gcd(trim(self.field.polynomial), self.coefficients)
        return len(common) > 1 and root_count(common, self.field.lo, self.field.hi) == 1
View source ↗
signmethod
sign(self, *, max_bisections: int=4096) -> int

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

Parameters

NameType & defaultContract
max_bisectionskeyword-onlyintDefault: 4096See the operation contract and implementation below.

Returns: int

Executed regression · algebraic root selection equality sign and inverse

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_algebraic_root_selection_equality_sign_and_inverse():
    assert root_count((-2, 0, 1), 1, 2) == 1
    with pytest.raises(ValueError):
        RealAlgebraicField((-2, 0, 1), -2, 2)
    with pytest.raises(ValueError):
        RealAlgebraicField((1, -2, 1), 0, 2)
    field = RealAlgebraicField.sqrt(2)
    t = field.generator
    assert (t * t - 2).is_zero()
    assert (t - Q(7, 5)).sign() == 1
    assert (t - Q(3, 2)).sign() == -1
    assert (t * t.inverse() - 1).is_zero()
    assert (RealAlgebraicField.sqrt(Q(9, 4)).generator - Q(3, 2)).is_zero()
    # Reducible primitives select a root; equality is not coefficient equality.
    reducible = RealAlgebraicField((0, -1, 0, 1), Q(1, 2), Q(3, 2))
    assert (reducible.generator - 1).is_zero()
    with pytest.raises(ZeroDivisionError):
        (reducible.generator + 1).inverse()
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_algebraic_root_selection_equality_sign_and_inverse" -q
Method implementation
    def sign(self, *, max_bisections: int = 4096) -> int:
        if self.is_zero():
            return 0
        lo, hi = rational(self.field.lo), rational(self.field.hi)
        primitive = trim(self.field.polynomial)
        for _ in range(max_bisections):
            # Exact interval Horner on rational endpoints.
            a = b = Fraction(0)
            for c in reversed(self.coefficients):
                products = (a * lo, a * hi, b * lo, b * hi)
                a, b = min(products) + c, max(products) + c
            if a > 0:
                return 1
            if b < 0:
                return -1
            mid = (lo + hi) / 2
            if evaluate(primitive, mid) == 0:
                value = evaluate(self.coefficients, mid)
                return 1 if value > 0 else -1
            if root_count(primitive, lo, mid):
                hi = mid
            else:
                lo = mid
        raise ArithmeticError("algebraic sign refinement budget exhausted")
View source ↗
Read the implementation
class AlgebraicNumber:
    field: RealAlgebraicField
    coefficients: UPoly

    def __post_init__(self) -> None:
        object.__setattr__(
            self, "coefficients", divide(trim(self.coefficients), trim(self.field.polynomial))[1]
        )

    def _coerce(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        out = other if isinstance(other, AlgebraicNumber) else self.field.constant(other)
        if out.field != self.field:
            raise ValueError("algebraic primitive elements differ")
        return out

    def __add__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        return self.field.number(add(self.coefficients, self._coerce(other).coefficients))

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

    def __neg__(self) -> AlgebraicNumber:
        return self.field.number(scale(self.coefficients, -1))

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

    def __rsub__(self, other: Rational) -> AlgebraicNumber:
        return -self + other

    def __mul__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        return self.field.number(multiply(self.coefficients, self._coerce(other).coefficients))

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

    def inverse(self) -> AlgebraicNumber:
        a, b = trim(self.field.polynomial), self.coefficients
        u: UPoly = ()
        v: UPoly = (Fraction(1),)
        while b:
            q, rem = divide(a, b)
            a, b, u, v = b, rem, v, add(u, scale(multiply(q, v), -1))
        if len(a) != 1:
            raise ZeroDivisionError(
                "nonunit denominator; refine the primitive polynomial if necessary"
            )
        return self.field.number(scale(u, 1 / a[0]))

    def __truediv__(self, other: AlgebraicNumber | Rational) -> AlgebraicNumber:
        return self * self._coerce(other).inverse()

    def __pow__(self, n: int) -> AlgebraicNumber:
        if type(n) is not int:
            raise TypeError("algebraic powers must be integers")
        if n < 0:
            return self.inverse() ** -n
        out, base = self.field.constant(1), self
        while n:
            if n & 1:
                out = out * base
            n //= 2
            if n:
                base = base * base
        return out

    def is_zero(self) -> bool:
        if not self.coefficients:
            return True
        common = gcd(trim(self.field.polynomial), self.coefficients)
        return len(common) > 1 and root_count(common, self.field.lo, self.field.hi) == 1

    def sign(self, *, max_bisections: int = 4096) -> int:
        if self.is_zero():
            return 0
        lo, hi = rational(self.field.lo), rational(self.field.hi)
        primitive = trim(self.field.polynomial)
        for _ in range(max_bisections):
            # Exact interval Horner on rational endpoints.
            a = b = Fraction(0)
            for c in reversed(self.coefficients):
                products = (a * lo, a * hi, b * lo, b * hi)
                a, b = min(products) + c, max(products) + c
            if a > 0:
                return 1
            if b < 0:
                return -1
            mid = (lo + hi) / 2
            if evaluate(primitive, mid) == 0:
                value = evaluate(self.coefficients, mid)
                return 1 if value > 0 else -1
            if root_count(primitive, lo, mid):
                hi = mid
            else:
                lo = mid
        raise ArithmeticError("algebraic sign refinement budget exhausted")
Other public import paths
  • omnibias.core.realization.AlgebraicNumber
  • omnibias.core.realization.algebraic.AlgebraicNumber
CLASS

RealAlgebraicField​

omnibias.core.realization.RealAlgebraicFieldSource ↗
class RealAlgebraicField

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
polynomialdataclass fieldtuple[Rational, ...]RequiredSee the operation contract and implementation below.
lodataclass fieldRationalRequiredSee the operation contract and implementation below.
hidataclass fieldRationalRequiredSee the operation contract and implementation below.
Executed regression · generic algebra replay is exact and emits both registers

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_generic_algebra_replay_is_exact_and_emits_both_registers(certificate):
    assert verify_replay_certificate(certificate)
    assert "decide +kernel" in generate_replay_obligation(certificate)
    assert "OmnibiasAnalytic.RealizationAlgebra" in generate_replay_obligation(
        certificate, mathlib=True
    )
python -m pytest "packages/omnibias-core/tests/proof/test_realization_algebra_replay.py::test_generic_algebra_replay_is_exact_and_emits_both_registers[certificate0]" -q
Regression example · algebraic root selection equality sign and inverse

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_algebraic_root_selection_equality_sign_and_inverse():
    assert root_count((-2, 0, 1), 1, 2) == 1
    with pytest.raises(ValueError):
        RealAlgebraicField((-2, 0, 1), -2, 2)
    with pytest.raises(ValueError):
        RealAlgebraicField((1, -2, 1), 0, 2)
    field = RealAlgebraicField.sqrt(2)
    t = field.generator
    assert (t * t - 2).is_zero()
    assert (t - Q(7, 5)).sign() == 1
    assert (t - Q(3, 2)).sign() == -1
    assert (t * t.inverse() - 1).is_zero()
    assert (RealAlgebraicField.sqrt(Q(9, 4)).generator - Q(3, 2)).is_zero()
    # Reducible primitives select a root; equality is not coefficient equality.
    reducible = RealAlgebraicField((0, -1, 0, 1), Q(1, 2), Q(3, 2))
    assert (reducible.generator - 1).is_zero()
    with pytest.raises(ZeroDivisionError):
        (reducible.generator + 1).inverse()
python -m pytest packages/omnibias-core/tests/test_realization_algebra.py -k test_algebraic_root_selection_equality_sign_and_inverse -q

Fields & methods

polynomialfield
polynomial: tuple[Rational, ...]

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

View source ↗
lofield
lo: Rational

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

View source ↗
hifield
hi: Rational

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

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 len(p) < 2 or len(gcd(p, derivative(p))) != 1, raises ValueError('primitive polynomial must be nonconstant and square-free').
  • When root_count(p, self.lo, self.hi) != 1, raises ValueError('primitive interval must isolate exactly one real root').
Executed regression · generic algebra replay is exact and emits both registers

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_generic_algebra_replay_is_exact_and_emits_both_registers(certificate):
    assert verify_replay_certificate(certificate)
    assert "decide +kernel" in generate_replay_obligation(certificate)
    assert "OmnibiasAnalytic.RealizationAlgebra" in generate_replay_obligation(
        certificate, mathlib=True
    )
python -m pytest "packages/omnibias-core/tests/proof/test_realization_algebra_replay.py::test_generic_algebra_replay_is_exact_and_emits_both_registers[certificate0]" -q
Method implementation
    def __post_init__(self) -> None:
        p = trim(self.polynomial)
        if len(p) < 2 or len(gcd(p, derivative(p))) != 1:
            raise ValueError("primitive polynomial must be nonconstant and square-free")
        if root_count(p, self.lo, self.hi) != 1:
            raise ValueError("primitive interval must isolate exactly one real root")
        object.__setattr__(self, "polynomial", p)
        object.__setattr__(self, "lo", rational(self.lo))
        object.__setattr__(self, "hi", rational(self.hi))
View source ↗
numbermethod
number(self, coefficients: Sequence[Rational]) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def number(self, coefficients: Sequence[Rational]) -> AlgebraicNumber:
        return AlgebraicNumber(self, divide(trim(coefficients), trim(self.polynomial))[1])
View source ↗
constantmethod
constant(self, value: Rational) -> AlgebraicNumber

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

Parameters

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def constant(self, value: Rational) -> AlgebraicNumber:
        return self.number((rational(value),))
View source ↗
generatorproperty
generator(self) -> AlgebraicNumber

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

Returns: AlgebraicNumber

Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def generator(self) -> AlgebraicNumber:
        return self.number((0, 1))
View source ↗
sqrtmethod
sqrt(cls, value: Rational) -> RealAlgebraicField

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

Parameters

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

Returns: RealAlgebraicField

Validation & failure cases
  • When q <= 0, raises ValueError('positive radicand required').
Executed regression · random real binary networks are never excluded

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_random_real_binary_networks_are_never_excluded():
    rng = random.Random(802)
    for _ in range(16):
        a, b, c, d = [Q(rng.randrange(-3, 4)) for _ in range(4)]
        rows = []
        for _ in range(3):
            u, v = [Q(rng.randrange(-2, 3)) for _ in range(2)]
            rows.append([u * a * a + v * c * c, 2 * (u * a * b + v * c * d), u * b * b + v * d * d])
        report = classify_binary_quadratic(rows)
        assert report.status == "realizable" and report.witness.verify(report.source)
python -m pytest "packages/omnibias-core/tests/test_realization_algebra.py::test_random_real_binary_networks_are_never_excluded" -q
Method implementation
    def sqrt(cls, value: Rational) -> RealAlgebraicField:
        q = rational(value)
        if q <= 0:
            raise ValueError("positive radicand required")
        n, d = isqrt(q.numerator), isqrt(q.denominator)
        if n * n == q.numerator and d * d == q.denominator:
            r = Fraction(n, d)
            return cls((-r, 1), r - 1, r + 1)
        lower = isqrt(q.numerator // q.denominator)
        return cls((-q, 0, 1), lower, lower + 1)
View source ↗
Read the implementation
class RealAlgebraicField:
    polynomial: tuple[Rational, ...]
    lo: Rational
    hi: Rational

    def __post_init__(self) -> None:
        p = trim(self.polynomial)
        if len(p) < 2 or len(gcd(p, derivative(p))) != 1:
            raise ValueError("primitive polynomial must be nonconstant and square-free")
        if root_count(p, self.lo, self.hi) != 1:
            raise ValueError("primitive interval must isolate exactly one real root")
        object.__setattr__(self, "polynomial", p)
        object.__setattr__(self, "lo", rational(self.lo))
        object.__setattr__(self, "hi", rational(self.hi))

    def number(self, coefficients: Sequence[Rational]) -> AlgebraicNumber:
        return AlgebraicNumber(self, divide(trim(coefficients), trim(self.polynomial))[1])

    def constant(self, value: Rational) -> AlgebraicNumber:
        return self.number((rational(value),))

    @property
    def generator(self) -> AlgebraicNumber:
        return self.number((0, 1))

    @classmethod
    def sqrt(cls, value: Rational) -> RealAlgebraicField:
        q = rational(value)
        if q <= 0:
            raise ValueError("positive radicand required")
        n, d = isqrt(q.numerator), isqrt(q.denominator)
        if n * n == q.numerator and d * d == q.denominator:
            r = Fraction(n, d)
            return cls((-r, 1), r - 1, r + 1)
        lower = isqrt(q.numerator // q.denominator)
        return cls((-q, 0, 1), lower, lower + 1)
Other public import paths
  • omnibias.core.realization.RealAlgebraicField
  • omnibias.core.realization.algebraic.RealAlgebraicField
CONSTANT

UPoly​

omnibias.core.realization.algebraic.UPolySource ↗
UPoly = tuple[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
UPoly = tuple[Fraction, ...]
FUNCTION

root_count​

omnibias.core.realization.root_countSource ↗
root_count(p: Sequence[Rational], lo: Rational, hi: Rational) -> int

Distinct roots strictly between non-root rational endpoints.

Parameters

NameType & defaultContract
ppositional-or-keywordSequence[Rational]RequiredSee the operation contract and implementation below.
lopositional-or-keywordRationalRequiredSee the operation contract and implementation below.
hipositional-or-keywordRationalRequiredSee the operation contract and implementation below.
Returnsint
Explicit validation & failure cases
  • When lower >= upper or not evaluate(a, lower) or (not evaluate(a, upper)), raises ValueError('ordered non-root endpoints required').

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

Executed regression · generic algebra replay is exact and emits both registers

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_generic_algebra_replay_is_exact_and_emits_both_registers(certificate):
    assert verify_replay_certificate(certificate)
    assert "decide +kernel" in generate_replay_obligation(certificate)
    assert "OmnibiasAnalytic.RealizationAlgebra" in generate_replay_obligation(
        certificate, mathlib=True
    )
python -m pytest "packages/omnibias-core/tests/proof/test_realization_algebra_replay.py::test_generic_algebra_replay_is_exact_and_emits_both_registers[certificate0]" -q
Regression example · algebraic root selection equality sign and inverse

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_algebraic_root_selection_equality_sign_and_inverse():
    assert root_count((-2, 0, 1), 1, 2) == 1
    with pytest.raises(ValueError):
        RealAlgebraicField((-2, 0, 1), -2, 2)
    with pytest.raises(ValueError):
        RealAlgebraicField((1, -2, 1), 0, 2)
    field = RealAlgebraicField.sqrt(2)
    t = field.generator
    assert (t * t - 2).is_zero()
    assert (t - Q(7, 5)).sign() == 1
    assert (t - Q(3, 2)).sign() == -1
    assert (t * t.inverse() - 1).is_zero()
    assert (RealAlgebraicField.sqrt(Q(9, 4)).generator - Q(3, 2)).is_zero()
    # Reducible primitives select a root; equality is not coefficient equality.
    reducible = RealAlgebraicField((0, -1, 0, 1), Q(1, 2), Q(3, 2))
    assert (reducible.generator - 1).is_zero()
    with pytest.raises(ZeroDivisionError):
        (reducible.generator + 1).inverse()
python -m pytest packages/omnibias-core/tests/test_realization_algebra.py -k test_algebraic_root_selection_equality_sign_and_inverse -q
Read the implementation
def root_count(p: Sequence[Rational], lo: Rational, hi: Rational) -> int:
    """Distinct roots strictly between non-root rational endpoints."""
    a, lower, upper = trim(p), rational(lo), rational(hi)
    if lower >= upper or not evaluate(a, lower) or not evaluate(a, upper):
        raise ValueError("ordered non-root endpoints required")
    if len(a) <= 1:
        return 0
    seq = sturm_sequence(a)

    def variations(x: Fraction) -> int:
        signs = [(v > 0) for q in seq if (v := evaluate(q, x)) != 0]
        return sum(a != b for a, b in zip(signs[:-1], signs[1:], strict=True))

    return variations(lower) - variations(upper)
Other public import paths
  • omnibias.core.realization.root_count
  • omnibias.core.realization.algebraic.root_count
FUNCTION

sturm_sequence​

omnibias.core.realization.algebraic.sturm_sequenceSource ↗
sturm_sequence(p: Sequence[Rational]) -> tuple[UPoly, ...]

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

Parameters

NameType & defaultContract
ppositional-or-keywordSequence[Rational]RequiredSee the operation contract and implementation below.
Returnstuple[UPoly, ...]
Explicit validation & failure cases
  • When len(a) < 2, raises ValueError('root counting requires a nonconstant polynomial').

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

Executed regression · generic algebra replay is exact and emits both registers

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_generic_algebra_replay_is_exact_and_emits_both_registers(certificate):
    assert verify_replay_certificate(certificate)
    assert "decide +kernel" in generate_replay_obligation(certificate)
    assert "OmnibiasAnalytic.RealizationAlgebra" in generate_replay_obligation(
        certificate, mathlib=True
    )
python -m pytest "packages/omnibias-core/tests/proof/test_realization_algebra_replay.py::test_generic_algebra_replay_is_exact_and_emits_both_registers[certificate0]" -q
Read the implementation
def sturm_sequence(p: Sequence[Rational]) -> tuple[UPoly, ...]:
    a = trim(p)
    if len(a) < 2:
        raise ValueError("root counting requires a nonconstant polynomial")
    b = derivative(a)
    seq = [a, b]
    while b:
        rem = scale(divide(a, b)[1], -1)
        if not rem:
            break
        seq.append(rem)
        a, b = b, rem
    return tuple(seq)