omnibias.core.verified.affine
Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.
import omnibias.core.verified.affineModule 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.
AffineForm
omnibias.core.verified.AffineFormSource ↗class AffineFormA 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
| Name | Type & default | Contract |
|---|---|---|
centerpositional-or-keyword | floatRequired | The central value x_0. |
deviationspositional-or-keyword | dict[int, float] | NoneDefault: None | Mapping symbol_id -> coefficient of the *named* partial deviations. Zero coefficients are dropped on construction. |
errorpositional-or-keyword | floatDefault: 0.0 | The 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-15python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -qRegression 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 -qFields & methods
__init__method
__init__(self, center: float, deviations: dict[int, float] | None=None, error: float=0.0) -> NoneSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
centerpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
deviationspositional-or-keyword | dict[int, float] | NoneDefault: None | See the operation contract and implementation below. |
errorpositional-or-keyword | floatDefault: 0.0 | See the operation contract and implementation below. |
Returns: None
Validation & failure cases
- When
e < 0.0, raisesValueError('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-15python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -qMethod 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 = econstantmethod
constant(cls, value: IntervalLike) -> AffineFormA degenerate form for a constant (rounding pushed into e).
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuepositional-or-keyword | IntervalLikeRequired | See 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-15python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -qMethod 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)symbolmethod
symbol(cls, center: float, radius: float, symbol_id: int | None=None) -> AffineFormA form center + radius * eps on a fresh (or given) noise symbol.
Parameters
| Name | Type & default | Contract |
|---|---|---|
centerpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
radiuspositional-or-keyword | floatRequired | See the operation contract and implementation below. |
symbol_idpositional-or-keyword | int | NoneDefault: None | See the operation contract and implementation below. |
Returns: AffineForm
Validation & failure cases
- When
radius < 0.0, raisesValueError('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" -qMethod 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)})from_intervalmethod
from_interval(cls, iv: IntervalLike, symbol_id: int | None=None) -> AffineFormConvert an interval to a form, introducing one *fresh* noise symbol.
Correlations start fresh: two intervals converted separately get independent symbols (no spurious cancellation).
Parameters
| Name | Type & default | Contract |
|---|---|---|
ivpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
symbol_idpositional-or-keyword | int | NoneDefault: None | See 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)named_radiusmethod
named_radius(self) -> floatOutward-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-15python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -qMethod 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()))radiusmethod
radius(self) -> floatTotal 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-15python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -qMethod implementation
def radius(self) -> float:
"""Total outward-rounded radius ``sum_i |x_i| + e``."""
return _add_up(self.named_radius(), self.error)to_intervalmethod
to_interval(self) -> IntervalGuaranteed 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-15python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -qMethod 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)__neg__method
__neg__(self) -> AffineFormSee 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" -qMethod 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)__add__method
__add__(self, other: AffineForm | IntervalLike) -> AffineFormSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | AffineForm | IntervalLikeRequired | See 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" -qMethod 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))__sub__method
__sub__(self, other: AffineForm | IntervalLike) -> AffineFormSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | AffineForm | IntervalLikeRequired | See 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" -qMethod implementation
def __sub__(self, other: AffineForm | IntervalLike) -> AffineForm:
o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
return self.__add__(-o)__rsub__method
__rsub__(self, other: AffineForm | IntervalLike) -> AffineFormSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | AffineForm | IntervalLikeRequired | See 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 truthpython -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_interval_loses_the_correlation" -qMethod implementation
def __rsub__(self, other: AffineForm | IntervalLike) -> AffineForm:
o = other if isinstance(other, AffineForm) else AffineForm.constant(other)
return o.__add__(-self)__mul__method
__mul__(self, other: AffineForm | IntervalLike) -> AffineFormSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | AffineForm | IntervalLikeRequired | See 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 truthpython -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_interval_loses_the_correlation" -qMethod 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))apply_scalarmethod
apply_scalar(self, f_interval: Callable[[Interval], Interval], *, slope: float | None=None) -> AffineFormRigorous 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
| Name | Type & default | Contract |
|---|---|---|
f_intervalpositional-or-keyword | Callable[[Interval], Interval]Required | See the operation contract and implementation below. |
slopekeyword-only | float | NoneDefault: None | See 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.hipython -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_reciprocal_soundness_random" -qMethod 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))reciprocalmethod
reciprocal(self) -> AffineForm1 / self (requires the enclosure to exclude zero).
Returns: AffineForm
Validation & failure cases
- When
self.to_interval().contains_zero(), raisesZeroDivisionError('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" -qMethod 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())sqrtmethod
sqrt(self) -> AffineFormsqrt(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.hipython -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_sqrt_and_pow_soundness_random" -qMethod implementation
def sqrt(self) -> AffineForm:
"""``sqrt(self)`` (requires a non-negative enclosure)."""
return self.apply_scalar(lambda iv: iv.sqrt())__truediv__method
__truediv__(self, other: AffineForm | IntervalLike) -> AffineFormSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | AffineForm | IntervalLikeRequired | See 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())__rtruediv__method
__rtruediv__(self, other: AffineForm | IntervalLike) -> AffineFormSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | AffineForm | IntervalLikeRequired | See 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())__pow__method
__pow__(self, n: int) -> AffineFormSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See 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.hipython -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_sqrt_and_pow_soundness_random" -qMethod 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__repr__method
__repr__(self) -> strSee 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})"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.
errorattribute
error = eThe non-negative anonymous radius e accumulating rounding and non-affine remainders. Treated as an independent symbol on every use.
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.AffineFormomnibias.core.verified.affine.AffineForm
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
| Name | Type & default | Contract |
|---|---|---|
ivspositional-or-keyword | list[IntervalLike]Required | See the operation contract and implementation below. |
list[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_intervalsomnibias.core.verified.affine.from_intervals
new_noise_symbol
omnibias.core.verified.new_noise_symbolSource ↗new_noise_symbol() -> intReturn a fresh, never-reused noise-symbol identifier.
intExecuted 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" -qRegression 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.hipython -m pytest packages/omnibias-core/tests/verified/test_affine.py -k test_reciprocal_soundness_random -qRead 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_symbolomnibias.core.verified.affine.new_noise_symbol