Skip to main content

omnibias.core.verified.affine

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

Rigorous affine arithmetic (zonotopes) on top of Interval.

Interval arithmetic loses every correlation between operands -- it cannot see that x - x = 0 -- so repeated operations suffer the *dependency* and *wrapping* blow-up. Affine arithmetic (Stolfi & de Figueiredo) fixes this by tracking each quantity as a first-order form in shared *noise symbols* eps_i in [-1, 1]:

\hat x = x_0 + \sum_{i} x_i\,\varepsilon_i \; (\pm\, e\,\varepsilon_e),

where the named x_i carry correlations exactly and e \ge 0 is an *anonymous* radius that rigorously absorbs every rounding error and every non-affine remainder. Two forms that share eps_i cancel that component exactly under subtraction, which is what defeats wrapping in the validated Lohner flow and tightens the Taylor-model neural-net verifier.

Rigor

Every floating-point coefficient is computed through Interval's outward-directed rounding: the *midpoint* becomes the stored float and the *radius* is accumulated into the anonymous error term e. Hence the stored form provably encloses the true real quantity for **all** admissible noise assignments. AffineForm.to_interval collapses the form back to a guaranteed enclosure [x_0 - R, x_0 + R] with R = sum_i |x_i| + e (rounded outward).

The non-affine operations (AffineForm.apply_scalar and the reciprocal / sqrt built on it) linearise f with an arbitrary slope alpha and bound the residual f(x) - alpha x by the *interval* enclosure f([X]) - alpha[X]; correctness is independent of the slope, so any alpha is sound and the secant slope merely minimises the added radius.

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

AffineForm​

omnibias.core.verified.AffineFormSource ↗
class AffineForm

A rigorous first-order affine form in shared noise symbols.

Parameters

center: The central value x_0. deviations: Mapping symbol_id -> coefficient of the *named* partial deviations. Zero coefficients are dropped on construction. error: The non-negative anonymous radius e accumulating rounding and non-affine remainders. Treated as an independent symbol on every use.

Parameters

NameType & defaultContract
centerpositional-or-keywordfloatRequiredThe central value x_0.
deviationspositional-or-keyworddict[int, float] | NoneDefault: NoneMapping symbol_id -> coefficient of the *named* partial deviations. Zero coefficients are dropped on construction.
errorpositional-or-keywordfloatDefault: 0.0The non-negative anonymous radius e accumulating rounding and non-affine remainders. Treated as an independent symbol on every use.
Executed regression · constant is tight

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_constant_is_tight() -> None:
    a = AffineForm.constant(2.5)
    iv = a.to_interval()
    assert iv.lo <= 2.5 <= iv.hi
    assert iv.width < 1e-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Regression example · reciprocal through zero rejected

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_reciprocal_through_zero_rejected() -> None:
    x = AffineForm.symbol(0.0, 1.0)  # encloses [-1, 1]
    with pytest.raises(ZeroDivisionError):
        x.reciprocal()
python -m pytest packages/omnibias-core/tests/verified/test_affine.py -k test_reciprocal_through_zero_rejected -q

Fields & methods

__init__method
__init__(self, center: float, deviations: dict[int, float] | None=None, error: float=0.0) -> None

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

Parameters

NameType & defaultContract
centerpositional-or-keywordfloatRequiredSee the operation contract and implementation below.
deviationspositional-or-keyworddict[int, float] | NoneDefault: NoneSee the operation contract and implementation below.
errorpositional-or-keywordfloatDefault: 0.0See the operation contract and implementation below.

Returns: None

Validation & failure cases
  • When e < 0.0, raises ValueError('affine error radius must be non-negative').
Executed regression · constant is tight

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_constant_is_tight() -> None:
    a = AffineForm.constant(2.5)
    iv = a.to_interval()
    assert iv.lo <= 2.5 <= iv.hi
    assert iv.width < 1e-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Method implementation
    def __init__(
        self,
        center: float,
        deviations: dict[int, float] | None = None,
        error: float = 0.0,
    ) -> None:
        self.center = float(center)
        if deviations:
            self.deviations = {k: float(v) for k, v in deviations.items() if v != 0.0}
        else:
            self.deviations = {}
        e = float(error)
        if e < 0.0:
            raise ValueError("affine error radius must be non-negative")
        self.error = e
View source ↗
constantmethod
constant(cls, value: IntervalLike) -> AffineForm

A degenerate form for a constant (rounding pushed into e).

Parameters

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

Returns: AffineForm

Executed regression · constant is tight

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_constant_is_tight() -> None:
    a = AffineForm.constant(2.5)
    iv = a.to_interval()
    assert iv.lo <= 2.5 <= iv.hi
    assert iv.width < 1e-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Method implementation
    def constant(cls, value: IntervalLike) -> AffineForm:
        """A degenerate form for a constant (rounding pushed into ``e``)."""
        iv = Interval.from_value(value)
        return cls(iv.mid, {}, iv.rad)
View source ↗
symbolmethod
symbol(cls, center: float, radius: float, symbol_id: int | None=None) -> AffineForm

A form center + radius * eps on a fresh (or given) noise symbol.

Parameters

NameType & defaultContract
centerpositional-or-keywordfloatRequiredSee the operation contract and implementation below.
radiuspositional-or-keywordfloatRequiredSee the operation contract and implementation below.
symbol_idpositional-or-keywordint | NoneDefault: NoneSee the operation contract and implementation below.

Returns: AffineForm

Validation & failure cases
  • When radius < 0.0, raises ValueError('symbol radius must be non-negative').
Executed regression · reciprocal through zero rejected

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_reciprocal_through_zero_rejected() -> None:
    x = AffineForm.symbol(0.0, 1.0)  # encloses [-1, 1]
    with pytest.raises(ZeroDivisionError):
        x.reciprocal()
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_reciprocal_through_zero_rejected" -q
Method implementation
    def symbol(cls, center: float, radius: float, symbol_id: int | None = None) -> AffineForm:
        """A form ``center + radius * eps`` on a fresh (or given) noise symbol."""
        if radius < 0.0:
            raise ValueError("symbol radius must be non-negative")
        sid = new_noise_symbol() if symbol_id is None else symbol_id
        return cls(center, {sid: float(radius)})
View source ↗
from_intervalmethod
from_interval(cls, iv: IntervalLike, symbol_id: int | None=None) -> AffineForm

Convert an interval to a form, introducing one *fresh* noise symbol.

Correlations start fresh: two intervals converted separately get independent symbols (no spurious cancellation).

Parameters

NameType & defaultContract
ivpositional-or-keywordIntervalLikeRequiredSee the operation contract and implementation below.
symbol_idpositional-or-keywordint | NoneDefault: NoneSee the operation contract and implementation below.

Returns: AffineForm

Method implementation
    def from_interval(cls, iv: IntervalLike, symbol_id: int | None = None) -> AffineForm:
        """Convert an interval to a form, introducing one *fresh* noise symbol.

        Correlations start fresh: two intervals converted separately get
        independent symbols (no spurious cancellation).
        """
        interval = Interval.from_value(iv)
        return cls.symbol(interval.mid, interval.rad, symbol_id)
View source ↗
named_radiusmethod
named_radius(self) -> float

Outward-rounded sum_i |x_i| over the named deviations only.

Returns: float

Executed regression · constant is tight

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_constant_is_tight() -> None:
    a = AffineForm.constant(2.5)
    iv = a.to_interval()
    assert iv.lo <= 2.5 <= iv.hi
    assert iv.width < 1e-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Method implementation
    def named_radius(self) -> float:
        """Outward-rounded ``sum_i |x_i|`` over the named deviations only."""
        return _add_up(*(abs(c) for c in self.deviations.values()))
View source ↗
radiusmethod
radius(self) -> float

Total outward-rounded radius sum_i |x_i| + e.

Returns: float

Executed regression · constant is tight

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_constant_is_tight() -> None:
    a = AffineForm.constant(2.5)
    iv = a.to_interval()
    assert iv.lo <= 2.5 <= iv.hi
    assert iv.width < 1e-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Method implementation
    def radius(self) -> float:
        """Total outward-rounded radius ``sum_i |x_i| + e``."""
        return _add_up(self.named_radius(), self.error)
View source ↗
to_intervalmethod
to_interval(self) -> Interval

Guaranteed enclosure [center - R, center + R] (outward rounded).

Returns: Interval

Executed regression · constant is tight

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_constant_is_tight() -> None:
    a = AffineForm.constant(2.5)
    iv = a.to_interval()
    assert iv.lo <= 2.5 <= iv.hi
    assert iv.width < 1e-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Method implementation
    def to_interval(self) -> Interval:
        """Guaranteed enclosure ``[center - R, center + R]`` (outward rounded)."""
        r = self.radius()
        return Interval.point(self.center) + Interval(-r, r)
View source ↗
__neg__method
__neg__(self) -> AffineForm

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

Returns: AffineForm

Executed regression · subtraction cancels shared symbol exactly

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_subtraction_cancels_shared_symbol_exactly() -> None:
    x = AffineForm.symbol(3.0, 2.0)
    z = x - x
    iv = z.to_interval()
    assert iv.lo <= 0.0 <= iv.hi
    assert iv.width < 1e-12  # dependency seen: x - x = 0, not [-4, 4]
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_subtraction_cancels_shared_symbol_exactly" -q
Method implementation
    def __neg__(self) -> AffineForm:
        # Negation is exact in IEEE-754 (no rounding).
        return AffineForm(-self.center, {k: -v for k, v in self.deviations.items()}, self.error)
View source ↗
__add__method
__add__(self, other: AffineForm | IntervalLike) -> AffineForm

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

Parameters

NameType & defaultContract
otherpositional-or-keywordAffineForm | IntervalLikeRequiredSee the operation contract and implementation below.

Returns: AffineForm

Executed regression · subtraction cancels shared symbol exactly

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_subtraction_cancels_shared_symbol_exactly() -> None:
    x = AffineForm.symbol(3.0, 2.0)
    z = x - x
    iv = z.to_interval()
    assert iv.lo <= 0.0 <= iv.hi
    assert iv.width < 1e-12  # dependency seen: x - x = 0, not [-4, 4]
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_subtraction_cancels_shared_symbol_exactly" -q
Method implementation
    def __add__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        c_iv = Interval.point(self.center) + Interval.point(o.center)
        carry = c_iv.rad
        devs: dict[int, float] = {}
        for sid in self.deviations.keys() | o.deviations.keys():
            term = Interval.point(self.deviations.get(sid, 0.0)) + Interval.point(
                o.deviations.get(sid, 0.0)
            )
            if term.lo != 0.0 or term.hi != 0.0:
                devs[sid] = term.mid
                carry = _add_up(carry, term.rad)
        return AffineForm(c_iv.mid, devs, _add_up(self.error, o.error, carry))
View source ↗
__sub__method
__sub__(self, other: AffineForm | IntervalLike) -> AffineForm

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

Parameters

NameType & defaultContract
otherpositional-or-keywordAffineForm | IntervalLikeRequiredSee the operation contract and implementation below.

Returns: AffineForm

Executed regression · subtraction cancels shared symbol exactly

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_subtraction_cancels_shared_symbol_exactly() -> None:
    x = AffineForm.symbol(3.0, 2.0)
    z = x - x
    iv = z.to_interval()
    assert iv.lo <= 0.0 <= iv.hi
    assert iv.width < 1e-12  # dependency seen: x - x = 0, not [-4, 4]
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_subtraction_cancels_shared_symbol_exactly" -q
Method implementation
    def __sub__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return self.__add__(-o)
View source ↗
__rsub__method
__rsub__(self, other: AffineForm | IntervalLike) -> AffineForm

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

Parameters

NameType & defaultContract
otherpositional-or-keywordAffineForm | IntervalLikeRequiredSee the operation contract and implementation below.

Returns: AffineForm

Executed regression · interval loses the correlation

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_interval_loses_the_correlation() -> None:
    # x*(1 - x) on x in [0, 1]: true range [0, 1/4]; naive interval gives [0, 1].
    x = AffineForm.symbol(0.5, 0.5)
    affine = (x * (1.0 - x)).to_interval()
    naive = Interval(0.0, 1.0) * (1.0 - Interval(0.0, 1.0))
    assert affine.width < naive.width
    assert affine.lo <= 0.0 and affine.hi >= 0.25  # still encloses the truth
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_interval_loses_the_correlation" -q
Method implementation
    def __rsub__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return o.__add__(-self)
View source ↗
__mul__method
__mul__(self, other: AffineForm | IntervalLike) -> AffineForm

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

Parameters

NameType & defaultContract
otherpositional-or-keywordAffineForm | IntervalLikeRequiredSee the operation contract and implementation below.

Returns: AffineForm

Executed regression · interval loses the correlation

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_interval_loses_the_correlation() -> None:
    # x*(1 - x) on x in [0, 1]: true range [0, 1/4]; naive interval gives [0, 1].
    x = AffineForm.symbol(0.5, 0.5)
    affine = (x * (1.0 - x)).to_interval()
    naive = Interval(0.0, 1.0) * (1.0 - Interval(0.0, 1.0))
    assert affine.width < naive.width
    assert affine.lo <= 0.0 and affine.hi >= 0.25  # still encloses the truth
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_interval_loses_the_correlation" -q
Method implementation
    def __mul__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        x0, y0 = self.center, o.center
        z_iv = Interval.point(x0) * Interval.point(y0)
        carry = z_iv.rad
        devs: dict[int, float] = {}
        for sid in self.deviations.keys() | o.deviations.keys():
            xi = self.deviations.get(sid, 0.0)
            yi = o.deviations.get(sid, 0.0)
            term = Interval.point(x0) * Interval.point(yi) + Interval.point(y0) * Interval.point(xi)
            if term.lo != 0.0 or term.hi != 0.0:
                devs[sid] = term.mid
                carry = _add_up(carry, term.rad)
        # Non-affine remainder (x - x0)(y - y0) plus the linear error-symbol
        # contributions |x0| e_y + |y0| e_x, all bounded outward.
        rx = _add_up(self.named_radius(), self.error)
        ry = _add_up(o.named_radius(), o.error)
        quad = _mul_up(rx, ry)
        lin_err = _add_up(_mul_up(abs(x0), o.error), _mul_up(abs(y0), self.error))
        return AffineForm(z_iv.mid, devs, _add_up(lin_err, quad, carry))
View source ↗
apply_scalarmethod
apply_scalar(self, f_interval: Callable[[Interval], Interval], *, slope: float | None=None) -> AffineForm

Rigorous affine enclosure of f(self) for a scalar function.

f_interval must return a guaranteed enclosure of f over any input interval. The form is linearised as alpha * self + beta and the residual f(x) - alpha x is bounded by the interval f([X]) - alpha[X]; the slope only affects tightness, never soundness.

Parameters

NameType & defaultContract
f_intervalpositional-or-keywordCallable[[Interval], Interval]RequiredSee the operation contract and implementation below.
slopekeyword-onlyfloat | NoneDefault: NoneSee the operation contract and implementation below.

Returns: AffineForm

Executed regression · reciprocal soundness random

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_reciprocal_soundness_random() -> None:
    rng = random.Random(2)
    sid = new_noise_symbol()
    for _ in range(200):
        x = AffineForm(rng.uniform(3.0, 6.0), {sid: rng.uniform(-1.0, 1.0)})
        z = x.reciprocal()
        for _ in range(8):
            a = {sid: rng.uniform(-1, 1)}
            truth = 1 / _exact_value(x, a)
            enc = _realize(z, a)
            assert enc.lo <= truth <= enc.hi
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_reciprocal_soundness_random" -q
Method implementation
    def apply_scalar(
        self,
        f_interval: Callable[[Interval], Interval],
        *,
        slope: float | None = None,
    ) -> AffineForm:
        r"""Rigorous affine enclosure of ``f(self)`` for a scalar function.

        ``f_interval`` must return a guaranteed enclosure of ``f`` over any input
        interval.  The form is linearised as ``alpha * self + beta`` and the
        residual ``f(x) - alpha x`` is bounded by the interval
        ``f([X]) - alpha[X]``; the slope only affects tightness, never soundness.
        """
        x = self.to_interval()
        if slope is None:
            if x.hi > x.lo:
                fa = f_interval(Interval.point(x.lo)).mid
                fb = f_interval(Interval.point(x.hi)).mid
                slope = (fb - fa) / (x.hi - x.lo)
            else:
                slope = 0.0
        residual = f_interval(x) - Interval.point(slope) * x
        z = self.__mul__(slope) + Interval.point(residual.mid)
        return AffineForm(z.center, z.deviations, _add_up(z.error, residual.rad))
View source ↗
reciprocalmethod
reciprocal(self) -> AffineForm

1 / self (requires the enclosure to exclude zero).

Returns: AffineForm

Validation & failure cases
  • When self.to_interval().contains_zero(), raises ZeroDivisionError('affine reciprocal requires 0 outside the enclosure').
Executed regression · reciprocal through zero rejected

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_reciprocal_through_zero_rejected() -> None:
    x = AffineForm.symbol(0.0, 1.0)  # encloses [-1, 1]
    with pytest.raises(ZeroDivisionError):
        x.reciprocal()
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_reciprocal_through_zero_rejected" -q
Method implementation
    def reciprocal(self) -> AffineForm:
        """``1 / self`` (requires the enclosure to exclude zero)."""
        if self.to_interval().contains_zero():
            raise ZeroDivisionError("affine reciprocal requires 0 outside the enclosure")
        return self.apply_scalar(lambda iv: iv.reciprocal())
View source ↗
sqrtmethod
sqrt(self) -> AffineForm

sqrt(self) (requires a non-negative enclosure).

Returns: AffineForm

Executed regression · sqrt and pow soundness random

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_sqrt_and_pow_soundness_random() -> None:
    rng = random.Random(3)
    sid = new_noise_symbol()
    for _ in range(200):
        x = AffineForm(rng.uniform(3.0, 6.0), {sid: rng.uniform(-1.0, 1.0)})
        zr = x.sqrt()
        zp = x**3
        for _ in range(8):
            a = {sid: rng.uniform(-1, 1)}
            xa = _exact_value(x, a)
            er, ep = _realize(zr, a), _realize(zp, a)
            assert er.lo <= math.sqrt(xa) <= er.hi
            assert ep.lo <= xa**3 <= ep.hi
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_sqrt_and_pow_soundness_random" -q
Method implementation
    def sqrt(self) -> AffineForm:
        """``sqrt(self)`` (requires a non-negative enclosure)."""
        return self.apply_scalar(lambda iv: iv.sqrt())
View source ↗
__truediv__method
__truediv__(self, other: AffineForm | IntervalLike) -> AffineForm

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

Parameters

NameType & defaultContract
otherpositional-or-keywordAffineForm | IntervalLikeRequiredSee the operation contract and implementation below.

Returns: AffineForm

Method implementation
    def __truediv__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return self.__mul__(o.reciprocal())
View source ↗
__rtruediv__method
__rtruediv__(self, other: AffineForm | IntervalLike) -> AffineForm

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

Parameters

NameType & defaultContract
otherpositional-or-keywordAffineForm | IntervalLikeRequiredSee the operation contract and implementation below.

Returns: AffineForm

Method implementation
    def __rtruediv__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return o.__mul__(self.reciprocal())
View source ↗
__pow__method
__pow__(self, n: int) -> AffineForm

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

Parameters

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

Returns: AffineForm

Executed regression · sqrt and pow soundness random

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_sqrt_and_pow_soundness_random() -> None:
    rng = random.Random(3)
    sid = new_noise_symbol()
    for _ in range(200):
        x = AffineForm(rng.uniform(3.0, 6.0), {sid: rng.uniform(-1.0, 1.0)})
        zr = x.sqrt()
        zp = x**3
        for _ in range(8):
            a = {sid: rng.uniform(-1, 1)}
            xa = _exact_value(x, a)
            er, ep = _realize(zr, a), _realize(zp, a)
            assert er.lo <= math.sqrt(xa) <= er.hi
            assert ep.lo <= xa**3 <= ep.hi
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_sqrt_and_pow_soundness_random" -q
Method implementation
    def __pow__(self, n: int) -> AffineForm:
        if n < 0:
            return self.reciprocal().__pow__(-n)
        result = AffineForm.constant(1.0)
        base = self
        e = n
        while e > 0:
            if e & 1:
                result = result * base
            e >>= 1
            if e > 0:
                base = base * base
        return result
View source ↗
__repr__method
__repr__(self) -> str

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

Returns: str

Method implementation
    def __repr__(self) -> str:
        body = " + ".join(f"{c!r}*e{sid}" for sid, c in sorted(self.deviations.items()))
        tail = f" +/- {self.error!r}" if self.error else ""
        return f"AffineForm({self.center!r}{' + ' + body if body else ''}{tail})"
View source ↗
centerattribute
center = float(center)

The central value x_0.

View source ↗
deviationsattribute
deviations = {k: float(v) for k, v in deviations.items() if v != 0.0}

Mapping symbol_id -> coefficient of the *named* partial deviations. Zero coefficients are dropped on construction.

View source ↗
errorattribute
error = e

The non-negative anonymous radius e accumulating rounding and non-affine remainders. Treated as an independent symbol on every use.

View source ↗
Read the implementation
class AffineForm:
    r"""A rigorous first-order affine form in shared noise symbols.

    Parameters
    ----------
    center:
        The central value ``x_0``.
    deviations:
        Mapping ``symbol_id -> coefficient`` of the *named* partial deviations.
        Zero coefficients are dropped on construction.
    error:
        The non-negative anonymous radius ``e`` accumulating rounding and
        non-affine remainders.  Treated as an independent symbol on every use.
    """

    __slots__ = ("center", "deviations", "error")

    def __init__(
        self,
        center: float,
        deviations: dict[int, float] | None = None,
        error: float = 0.0,
    ) -> None:
        self.center = float(center)
        if deviations:
            self.deviations = {k: float(v) for k, v in deviations.items() if v != 0.0}
        else:
            self.deviations = {}
        e = float(error)
        if e < 0.0:
            raise ValueError("affine error radius must be non-negative")
        self.error = e

    # ----- constructors -------------------------------------------------- #
    @classmethod
    def constant(cls, value: IntervalLike) -> AffineForm:
        """A degenerate form for a constant (rounding pushed into ``e``)."""
        iv = Interval.from_value(value)
        return cls(iv.mid, {}, iv.rad)

    @classmethod
    def symbol(cls, center: float, radius: float, symbol_id: int | None = None) -> AffineForm:
        """A form ``center + radius * eps`` on a fresh (or given) noise symbol."""
        if radius < 0.0:
            raise ValueError("symbol radius must be non-negative")
        sid = new_noise_symbol() if symbol_id is None else symbol_id
        return cls(center, {sid: float(radius)})

    @classmethod
    def from_interval(cls, iv: IntervalLike, symbol_id: int | None = None) -> AffineForm:
        """Convert an interval to a form, introducing one *fresh* noise symbol.

        Correlations start fresh: two intervals converted separately get
        independent symbols (no spurious cancellation).
        """
        interval = Interval.from_value(iv)
        return cls.symbol(interval.mid, interval.rad, symbol_id)

    # ----- queries ------------------------------------------------------- #
    def named_radius(self) -> float:
        """Outward-rounded ``sum_i |x_i|`` over the named deviations only."""
        return _add_up(*(abs(c) for c in self.deviations.values()))

    def radius(self) -> float:
        """Total outward-rounded radius ``sum_i |x_i| + e``."""
        return _add_up(self.named_radius(), self.error)

    def to_interval(self) -> Interval:
        """Guaranteed enclosure ``[center - R, center + R]`` (outward rounded)."""
        r = self.radius()
        return Interval.point(self.center) + Interval(-r, r)

    # ----- affine algebra ------------------------------------------------ #
    def __neg__(self) -> AffineForm:
        # Negation is exact in IEEE-754 (no rounding).
        return AffineForm(-self.center, {k: -v for k, v in self.deviations.items()}, self.error)

    def __add__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        c_iv = Interval.point(self.center) + Interval.point(o.center)
        carry = c_iv.rad
        devs: dict[int, float] = {}
        for sid in self.deviations.keys() | o.deviations.keys():
            term = Interval.point(self.deviations.get(sid, 0.0)) + Interval.point(
                o.deviations.get(sid, 0.0)
            )
            if term.lo != 0.0 or term.hi != 0.0:
                devs[sid] = term.mid
                carry = _add_up(carry, term.rad)
        return AffineForm(c_iv.mid, devs, _add_up(self.error, o.error, carry))

    __radd__ = __add__

    def __sub__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return self.__add__(-o)

    def __rsub__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return o.__add__(-self)

    def __mul__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        x0, y0 = self.center, o.center
        z_iv = Interval.point(x0) * Interval.point(y0)
        carry = z_iv.rad
        devs: dict[int, float] = {}
        for sid in self.deviations.keys() | o.deviations.keys():
            xi = self.deviations.get(sid, 0.0)
            yi = o.deviations.get(sid, 0.0)
            term = Interval.point(x0) * Interval.point(yi) + Interval.point(y0) * Interval.point(xi)
            if term.lo != 0.0 or term.hi != 0.0:
                devs[sid] = term.mid
                carry = _add_up(carry, term.rad)
        # Non-affine remainder (x - x0)(y - y0) plus the linear error-symbol
        # contributions |x0| e_y + |y0| e_x, all bounded outward.
        rx = _add_up(self.named_radius(), self.error)
        ry = _add_up(o.named_radius(), o.error)
        quad = _mul_up(rx, ry)
        lin_err = _add_up(_mul_up(abs(x0), o.error), _mul_up(abs(y0), self.error))
        return AffineForm(z_iv.mid, devs, _add_up(lin_err, quad, carry))

    __rmul__ = __mul__

    # ----- non-affine operations ----------------------------------------- #
    def apply_scalar(
        self,
        f_interval: Callable[[Interval], Interval],
        *,
        slope: float | None = None,
    ) -> AffineForm:
        r"""Rigorous affine enclosure of ``f(self)`` for a scalar function.

        ``f_interval`` must return a guaranteed enclosure of ``f`` over any input
        interval.  The form is linearised as ``alpha * self + beta`` and the
        residual ``f(x) - alpha x`` is bounded by the interval
        ``f([X]) - alpha[X]``; the slope only affects tightness, never soundness.
        """
        x = self.to_interval()
        if slope is None:
            if x.hi > x.lo:
                fa = f_interval(Interval.point(x.lo)).mid
                fb = f_interval(Interval.point(x.hi)).mid
                slope = (fb - fa) / (x.hi - x.lo)
            else:
                slope = 0.0
        residual = f_interval(x) - Interval.point(slope) * x
        z = self.__mul__(slope) + Interval.point(residual.mid)
        return AffineForm(z.center, z.deviations, _add_up(z.error, residual.rad))

    def reciprocal(self) -> AffineForm:
        """``1 / self`` (requires the enclosure to exclude zero)."""
        if self.to_interval().contains_zero():
            raise ZeroDivisionError("affine reciprocal requires 0 outside the enclosure")
        return self.apply_scalar(lambda iv: iv.reciprocal())

    def sqrt(self) -> AffineForm:
        """``sqrt(self)`` (requires a non-negative enclosure)."""
        return self.apply_scalar(lambda iv: iv.sqrt())

    def __truediv__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return self.__mul__(o.reciprocal())

    def __rtruediv__(self, other: AffineForm | IntervalLike) -> AffineForm:
        o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
        return o.__mul__(self.reciprocal())

    def __pow__(self, n: int) -> AffineForm:
        if n < 0:
            return self.reciprocal().__pow__(-n)
        result = AffineForm.constant(1.0)
        base = self
        e = n
        while e > 0:
            if e & 1:
                result = result * base
            e >>= 1
            if e > 0:
                base = base * base
        return result

    def __repr__(self) -> str:
        body = " + ".join(f"{c!r}*e{sid}" for sid, c in sorted(self.deviations.items()))
        tail = f" +/- {self.error!r}" if self.error else ""
        return f"AffineForm({self.center!r}{' + ' + body if body else ''}{tail})"
Other public import paths
  • omnibias.core.verified.AffineForm
  • omnibias.core.verified.affine.AffineForm
FUNCTION

from_intervals​

omnibias.core.verified.from_intervalsSource ↗
from_intervals(ivs: list[IntervalLike]) -> list[AffineForm]

Convert a list of intervals to forms, each on its own fresh symbol.

Parameters

NameType & defaultContract
ivspositional-or-keywordlist[IntervalLike]RequiredSee the operation contract and implementation below.
Returnslist[AffineForm]
Read the implementation
def from_intervals(ivs: list[IntervalLike]) -> list[AffineForm]:
    """Convert a list of intervals to forms, each on its own fresh symbol."""
    return [AffineForm.from_interval(iv) for iv in ivs]
Other public import paths
  • omnibias.core.verified.from_intervals
  • omnibias.core.verified.affine.from_intervals
FUNCTION

new_noise_symbol​

omnibias.core.verified.new_noise_symbolSource ↗
new_noise_symbol() -> int

Return a fresh, never-reused noise-symbol identifier.

Returnsint
Executed regression · reciprocal through zero rejected

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_reciprocal_through_zero_rejected() -> None:
    x = AffineForm.symbol(0.0, 1.0)  # encloses [-1, 1]
    with pytest.raises(ZeroDivisionError):
        x.reciprocal()
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_reciprocal_through_zero_rejected" -q
Regression example · reciprocal soundness random

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_reciprocal_soundness_random() -> None:
    rng = random.Random(2)
    sid = new_noise_symbol()
    for _ in range(200):
        x = AffineForm(rng.uniform(3.0, 6.0), {sid: rng.uniform(-1.0, 1.0)})
        z = x.reciprocal()
        for _ in range(8):
            a = {sid: rng.uniform(-1, 1)}
            truth = 1 / _exact_value(x, a)
            enc = _realize(z, a)
            assert enc.lo <= truth <= enc.hi
python -m pytest packages/omnibias-core/tests/verified/test_affine.py -k test_reciprocal_soundness_random -q
Read the implementation
def new_noise_symbol() -> int:
    """Return a fresh, never-reused noise-symbol identifier."""
    return next(_symbol_counter)
Other public import paths
  • omnibias.core.verified.new_noise_symbol
  • omnibias.core.verified.affine.new_noise_symbol