omnibias.core.verified.interval
Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.
import omnibias.core.verified.intervalModule contract & mathematical conventions
Rigorous floating-point interval arithmetic (pure stdlib).
Every operation returns an Interval that is *guaranteed* to enclose the
true real result for **all** points in the input intervals. Rigor comes from
*outward directed rounding*: an endpoint computed in IEEE round-to-nearest is
pushed one representable step outward with math.nextafter. For a single
IEEE-754 operation the rounding error is <= 0.5 ulp while one
math.nextafter step is 1 ulp in the outward direction, so the
inflated endpoints provably bracket the exact result.
This is the dependency-free substrate named in the omnibias certified-evidence backend
contract (mpfr_or_arb_outward_interval_backend); the transcendental
enclosures in omnibias.core.verified.transcend optionally sharpen the
base-point evaluations with mpmath when it is installed, but the algebra
here needs only the standard library.
Notes
- Powers use binary exponentiation by repeated interval multiplication so the
enclosure is rigorous for *every* exponent (a single
nextafterstep would not cover the multi-rounding error offloat.__pow__). - Division and reciprocal require the denominator interval to be bounded away
from zero; otherwise
ZeroDivisionErroris raised.
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.
Interval
omnibias.core.verified.IntervalSource ↗class IntervalDataclass 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.
A closed real interval [lo, hi] with lo <= hi and no NaN.
The constructor performs no rounding -- it assumes the endpoints already bracket the intended quantity.
Injecting scalars (mind the difference):
from_rational-- andfrom_valueforint/Fraction-- returns the *tightest outward-rounded* float interval enclosing the exact rational, e.g.from_rational(Fraction(1, 10))straddles the true1/10withlo < 1/10 < hi.point-- andfrom_valueforfloat-- injects the float as an *exact point*[x, x]with **no rounding**. This is rigorous when the float itself **is** the intended datum (a matrix entry, a measured coefficient). It does *not* enclose a different real that the float merely approximates:point(0.1)is the double0.1, not the rational1/10-- usefrom_rational(Fraction(1, 10))for that.
Parameters
| Name | Type & default | Contract |
|---|---|---|
lodataclass field | floatRequired | See the operation contract and implementation below. |
hidataclass field | floatRequired | See the operation contract and implementation below. |
Executed regression · width is outward
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_width_is_outward() -> None:
a = Interval(1.0, 1.0 + 2.0**-50)
assert a.width >= 2.0**-50python -m pytest "packages/omnibias-core/tests/verified/test_interval.py::test_width_is_outward" -qRegression example · empty interval raises
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_empty_interval_raises() -> None:
with pytest.raises(ValueError, match="empty interval"):
Interval(2.0, 1.0)python -m pytest packages/omnibias-core/tests/verified/test_interval.py -k test_empty_interval_raises -qFields & methods
lofield
lo: floatDeclared float field on Interval. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
Regression example · interval roundtrip is bit exact
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_roundtrip_is_bit_exact() -> None:
iv = Interval(0.1, 0.1 + 1e-16) # endpoints not exactly representable in decimal
again = decode_interval(encode_interval(iv))
assert again.lo == iv.lo
assert again.hi == iv.hipython -m pytest packages/omnibias-core/tests/test_certificate.py -k test_interval_roundtrip_is_bit_exact -qhifield
hi: floatDeclared float field on Interval. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
Regression example · interval roundtrip is bit exact
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_roundtrip_is_bit_exact() -> None:
iv = Interval(0.1, 0.1 + 1e-16) # endpoints not exactly representable in decimal
again = decode_interval(encode_interval(iv))
assert again.lo == iv.lo
assert again.hi == iv.hipython -m pytest packages/omnibias-core/tests/test_certificate.py -k test_interval_roundtrip_is_bit_exact -q__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
isnan(self.lo) or isnan(self.hi), raisesValueError('interval endpoints must not be NaN'). - When
self.lo > self.hi, raisesValueError(f'empty interval: lo={self.lo!r} > hi={self.hi!r}').
Executed regression · width is outward
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_width_is_outward() -> None:
a = Interval(1.0, 1.0 + 2.0**-50)
assert a.width >= 2.0**-50python -m pytest "packages/omnibias-core/tests/verified/test_interval.py::test_width_is_outward" -qMethod implementation
def __post_init__(self) -> None:
if isnan(self.lo) or isnan(self.hi):
raise ValueError("interval endpoints must not be NaN")
if self.lo > self.hi:
raise ValueError(f"empty interval: lo={self.lo!r} > hi={self.hi!r}")pointmethod
point(cls, x: float) -> IntervalExact degenerate interval [x, x] for the float x itself.
No rounding is applied, so this is rigorous only when x is the
intended datum. To enclose a real that x merely approximates (e.g.
the rational 1/10), use from_rational instead.
Parameters
| Name | Type & default | Contract |
|---|---|---|
xpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def point(cls, x: float) -> Interval:
"""Exact degenerate interval ``[x, x]`` for the float ``x`` itself.
No rounding is applied, so this is rigorous only when ``x`` is the
intended datum. To enclose a real that ``x`` merely approximates (e.g.
the rational ``1/10``), use :meth:`from_rational` instead.
"""
xf = float(x)
return cls(xf, xf)from_rationalmethod
from_rational(cls, q: Fraction | int) -> IntervalTightest float interval enclosing an exact rational/integer q.
Parameters
| Name | Type & default | Contract |
|---|---|---|
qpositional-or-keyword | Fraction | intRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def from_rational(cls, q: Fraction | int) -> Interval:
"""Tightest float interval enclosing an exact rational/integer ``q``."""
frac = Fraction(q)
f = float(frac)
lo = f
hi = f
as_frac = Fraction(f)
if as_frac > frac:
lo = _pred(f)
elif as_frac < frac:
hi = _succ(f)
return cls(lo, hi)from_valuemethod
from_value(cls, value: IntervalLike) -> IntervalPromote any IntervalLike to an Interval.
int / Fraction go through from_rational (tightest
outward-rounded enclosure of the exact rational); a float is
injected as an *exact point* [x, x] via point -- no
rounding, which is correct when the float is the literal datum (see the
class docstring for the rational-vs-float caveat).
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuepositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def from_value(cls, value: IntervalLike) -> Interval:
"""Promote any :data:`IntervalLike` to an :class:`Interval`.
``int`` / ``Fraction`` go through :meth:`from_rational` (tightest
outward-rounded enclosure of the exact rational); a ``float`` is
injected as an *exact point* ``[x, x]`` via :meth:`point` -- no
rounding, which is correct when the float is the literal datum (see the
class docstring for the rational-vs-float caveat).
"""
if isinstance(value, Interval):
return value
if isinstance(value, int | Fraction):
return cls.from_rational(value)
return cls.point(float(value))hullmethod
hull(cls, *values: IntervalLike) -> IntervalSmallest interval containing every argument.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuesvariadic positional | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
Validation & failure cases
- When
not values, raisesValueError('hull requires at least one value').
Executed regression · g2 non vacuous
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_g2_non_vacuous() -> None:
ex = worked_example()
assert float(ex["remainder_width"]) < 0.1
assert ex["vacuous"] is False
assert float(ex["width"]) < 0.1python -m pytest "packages/omnibias-core/tests/verified/test_tm_neuron.py::test_g2_non_vacuous" -qMethod implementation
def hull(cls, *values: IntervalLike) -> Interval:
"""Smallest interval containing every argument."""
if not values:
raise ValueError("hull requires at least one value")
ivs = [cls.from_value(v) for v in values]
return cls(min(iv.lo for iv in ivs), max(iv.hi for iv in ivs))midproperty
mid(self) -> floatA representable point near the midpoint (always inside the interval).
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 mid(self) -> float:
"""A representable point near the midpoint (always inside the interval)."""
m = 0.5 * (self.lo + self.hi)
if m < self.lo:
return self.lo
if m > self.hi:
return self.hi
return mradproperty
rad(self) -> floatAn outward-rounded radius: hi - mid (>= true radius).
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 rad(self) -> float:
"""An outward-rounded radius: ``hi - mid`` (>= true radius)."""
m = self.mid
return _succ(max(m - self.lo, self.hi - m))widthproperty
width(self) -> floatOutward-rounded width hi - lo.
Returns: float
Executed regression · width is outward
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_width_is_outward() -> None:
a = Interval(1.0, 1.0 + 2.0**-50)
assert a.width >= 2.0**-50python -m pytest "packages/omnibias-core/tests/verified/test_interval.py::test_width_is_outward" -qMethod implementation
def width(self) -> float:
"""Outward-rounded width ``hi - lo``."""
return _succ(self.hi - self.lo)magproperty
mag(self) -> floatMagnitude max |x| over the interval (outward rounded).
Returns: float
Executed regression · boundary residual empty is zero
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_boundary_residual_empty_is_zero() -> None:
assert certified_boundary_residual(_AFFINE, []).mag < 1e-300python -m pytest "packages/omnibias-core/tests/test_verified_pde_certificate.py::test_boundary_residual_empty_is_zero" -qMethod implementation
def mag(self) -> float:
"""Magnitude ``max |x|`` over the interval (outward rounded)."""
return _succ(max(abs(self.lo), abs(self.hi)))migproperty
mig(self) -> floatMignitude min |x| over the interval (0 if it straddles 0).
Returns: float
Executed regression · modulus lower bound zero when straddling origin
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_modulus_lower_bound_zero_when_straddling_origin() -> None:
box = ComplexInterval(Interval(-1.0, 1.0), Interval(-1.0, 1.0))
assert box.modulus().lo == 0.0python -m pytest "packages/omnibias-core/tests/test_verified_complex_interval.py::test_modulus_lower_bound_zero_when_straddling_origin" -qMethod implementation
def mig(self) -> float:
"""Mignitude ``min |x|`` over the interval (0 if it straddles 0)."""
if self.lo <= 0.0 <= self.hi:
return 0.0
return _pred(min(abs(self.lo), abs(self.hi)))containsmethod
contains(self, x: float) -> boolSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
xpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
Returns: bool
Executed regression · euler enclosure contains mpmath
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_euler_enclosure_contains_mpmath(n: int) -> None:
assert euler_enclosure(n).contains(float(mpmath.eulernum(n)))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_mpmath[10]" -qMethod implementation
def contains(self, x: float) -> bool:
return self.lo <= x <= self.hicontains_zeromethod
contains_zero(self) -> boolSee the class contract above and the exact method implementation below.
Returns: bool
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def contains_zero(self) -> bool:
return self.lo <= 0.0 <= self.hi__add__method
__add__(self, other: IntervalLike) -> IntervalSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · bernoulli enclosure contains exact
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_bernoulli_enclosure_contains_exact(n: int) -> None:
assert _encloses(bernoulli_enclosure(n), bernoulli_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_bernoulli_enclosure_contains_exact[10]" -qMethod implementation
def __add__(self, other: IntervalLike) -> Interval:
o = Interval.from_value(other)
return Interval(_pred(self.lo + o.lo), _succ(self.hi + o.hi))__neg__method
__neg__(self) -> IntervalSee the class contract above and the exact method implementation below.
Returns: Interval
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def __neg__(self) -> Interval:
return Interval(-self.hi, -self.lo)__sub__method
__sub__(self, other: IntervalLike) -> IntervalSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · dag large ball not certified
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_dag_large_ball_not_certified() -> None:
cert = certify_decoding_dag(_DIAMOND_EDGES, _DIAMOND, eps=5.0)
assert not cert.certifiedpython -m pytest "packages/omnibias-struct/tests/test_decode.py::test_dag_large_ball_not_certified" -qMethod implementation
def __sub__(self, other: IntervalLike) -> Interval:
o = Interval.from_value(other)
return Interval(_pred(self.lo - o.hi), _succ(self.hi - o.lo))__rsub__method
__rsub__(self, other: IntervalLike) -> IntervalSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
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: IntervalLike) -> Interval:
return Interval.from_value(other).__sub__(self)__mul__method
__mul__(self, other: IntervalLike) -> IntervalSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def __mul__(self, other: IntervalLike) -> Interval:
o = Interval.from_value(other)
products = (
self.lo * o.lo,
self.lo * o.hi,
self.hi * o.lo,
self.hi * o.hi,
)
return Interval(_pred(min(products)), _succ(max(products)))reciprocalmethod
reciprocal(self) -> Interval1 / self; requires the interval to exclude zero.
Returns: Interval
Validation & failure cases
- When
self.contains_zero(), raisesZeroDivisionError('interval reciprocal requires 0 outside [lo, hi]').
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def reciprocal(self) -> Interval:
"""``1 / self``; requires the interval to exclude zero."""
if self.contains_zero():
raise ZeroDivisionError("interval reciprocal requires 0 outside [lo, hi]")
return Interval(_pred(1.0 / self.hi), _succ(1.0 / self.lo))__truediv__method
__truediv__(self, other: IntervalLike) -> IntervalSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · manufactured solution is an exact zero
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_manufactured_solution_is_an_exact_zero() -> None:
problem, a_star = _scalar_problem()
residual = evaluate_residual(problem, a_star)
assert residual.norm().hi < 1e-12python -m pytest "packages/omnibias-core/tests/test_verified_radii_spectral.py::test_manufactured_solution_is_an_exact_zero" -qMethod implementation
def __truediv__(self, other: IntervalLike) -> Interval:
return self.__mul__(Interval.from_value(other).reciprocal())__rtruediv__method
__rtruediv__(self, other: IntervalLike) -> IntervalSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | IntervalLikeRequired | See the operation contract and implementation below. |
Returns: Interval
Method implementation
def __rtruediv__(self, other: IntervalLike) -> Interval:
return Interval.from_value(other).__mul__(self.reciprocal())__pow__method
__pow__(self, n: int) -> IntervalSee 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: Interval
Executed regression · signed root regimes against atan atanh
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_signed_root_regimes_against_atan_atanh(delta, value, p, endpoint):
with mp.workdps(100):
result = signed_root_primitive(delta, value, delta_order=p, endpoint_order=endpoint)
contains(result, root_reference(delta, value, p, endpoint))python -m pytest "packages/omnibias-core/tests/verified/test_asymptotic_jet.py::test_signed_root_regimes_against_atan_atanh[0-0--0.1--1.0]" -qMethod implementation
def __pow__(self, n: int) -> Interval:
return self.pow_int(n)pow_intmethod
pow_int(self, n: int) -> IntervalRigorous integer power via interval binary exponentiation.
For an even n the base is first folded through abs, so a
sign-straddling interval yields the tight [0, mag**n] enclosure rather
than a loose one polluted by spurious negative corner products (x**n is
non-negative for even n). This only tightens the result; non-straddling
intervals are unaffected.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: Interval
Executed regression · euler enclosure contains exact
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_euler_enclosure_contains_exact(n: int) -> None:
assert _encloses(euler_enclosure(n), euler_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_euler_enclosure_contains_exact[10]" -qMethod implementation
def pow_int(self, n: int) -> Interval:
"""Rigorous integer power via interval binary exponentiation.
For an even ``n`` the base is first folded through :meth:`abs`, so a
sign-straddling interval yields the tight ``[0, mag**n]`` enclosure rather
than a loose one polluted by spurious negative corner products (``x**n`` is
non-negative for even ``n``). This only tightens the result; non-straddling
intervals are unaffected.
"""
if n < 0:
return self.pow_int(-n).reciprocal()
result = Interval.point(1.0)
base = self.abs() if n % 2 == 0 else self
e = n
while e > 0:
if e & 1:
result = result * base
e >>= 1
if e > 0:
base = base * base
return resultabsmethod
abs(self) -> IntervalEnclosure of |x| over the interval.
Returns: Interval
Executed regression · bernoulli enclosure contains exact
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_bernoulli_enclosure_contains_exact(n: int) -> None:
assert _encloses(bernoulli_enclosure(n), bernoulli_number(n))python -m pytest "packages/omnibias-difference/tests/test_generating.py::test_bernoulli_enclosure_contains_exact[10]" -qMethod implementation
def abs(self) -> Interval:
"""Enclosure of ``|x|`` over the interval."""
if self.lo >= 0.0:
return self
if self.hi <= 0.0:
return -self
return Interval(0.0, _succ(max(-self.lo, self.hi)))sqrtmethod
sqrt(self) -> IntervalEnclosure of sqrt(x); requires lo >= 0.
math.sqrt is an IEEE-754 *correctly rounded* operation (error
<= 0.5 ulp), so a single outward nextafter step per endpoint is a
rigorous bracket. This is unlike the libm transcendentals (exp /
log), which are not guaranteed correctly rounded and therefore need the
wider omnibias.core.verified.transcend enclosures.
Returns: Interval
Validation & failure cases
- When
self.lo < 0.0, raisesValueError('sqrt requires a non-negative interval').
Executed regression · sqrt negative raises
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_negative_raises() -> None:
with pytest.raises(ValueError, match="non-negative"):
Interval(-1.0, 1.0).sqrt()python -m pytest "packages/omnibias-core/tests/verified/test_interval.py::test_sqrt_negative_raises" -qMethod implementation
def sqrt(self) -> Interval:
"""Enclosure of ``sqrt(x)``; requires ``lo >= 0``.
``math.sqrt`` is an IEEE-754 *correctly rounded* operation (error
``<= 0.5 ulp``), so a single outward ``nextafter`` step per endpoint is a
rigorous bracket. This is unlike the libm transcendentals (``exp`` /
``log``), which are not guaranteed correctly rounded and therefore need the
wider :mod:`omnibias.core.verified.transcend` enclosures.
"""
from math import sqrt as _sqrt
if self.lo < 0.0:
raise ValueError("sqrt requires a non-negative interval")
return Interval(_pred(_sqrt(self.lo)), _succ(_sqrt(self.hi)))intersectmethod
intersect(self, other: Interval) -> IntervalSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
otherpositional-or-keyword | IntervalRequired | See the operation contract and implementation below. |
Returns: Interval
Validation & failure cases
- When
lo > hi, raisesValueError('empty intersection').
Executed regression · run model requires actual when verify
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_run_model_requires_actual_when_verify() -> None:
with pytest.raises(ValueError, match="actual_fn"):
run_model_line_search(_QUARTIC_DERIVS, config=JetLineSearchConfig(order=4))python -m pytest "packages/omnibias-core/tests/test_line_search.py::test_run_model_requires_actual_when_verify" -qMethod implementation
def intersect(self, other: Interval) -> Interval:
lo = max(self.lo, other.lo)
hi = min(self.hi, other.hi)
if lo > hi:
raise ValueError("empty intersection")
return Interval(lo, hi)__repr__method
__repr__(self) -> strSee the class contract above and the exact method implementation below.
Returns: str
Executed regression · hermite expansion repr
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_hermite_expansion_repr() -> None:
expansion = HermiteExpansion.from_coeffs([1.0, 2.0])
text = repr(expansion)
assert "HermiteExpansion" in text
assert "order=1" in textpython -m pytest "packages/omnibias-core/tests/verified/test_hermite_basis.py::test_hermite_expansion_repr" -qMethod implementation
def __repr__(self) -> str:
return f"Interval([{self.lo!r}, {self.hi!r}])"Read the implementation
class Interval:
"""A closed real interval ``[lo, hi]`` with ``lo <= hi`` and no ``NaN``.
The constructor performs no rounding -- it assumes the endpoints already
bracket the intended quantity.
Injecting scalars (mind the difference):
- :meth:`from_rational` -- and :meth:`from_value` for ``int`` / ``Fraction``
-- returns the *tightest outward-rounded* float interval enclosing the
exact rational, e.g. ``from_rational(Fraction(1, 10))`` straddles the true
``1/10`` with ``lo < 1/10 < hi``.
- :meth:`point` -- and :meth:`from_value` for ``float`` -- injects the float
as an *exact point* ``[x, x]`` with **no rounding**. This is rigorous when
the float itself **is** the intended datum (a matrix entry, a measured
coefficient). It does *not* enclose a different real that the float merely
approximates: ``point(0.1)`` is the double ``0.1``, not the rational
``1/10`` -- use ``from_rational(Fraction(1, 10))`` for that.
"""
lo: float
hi: float
def __post_init__(self) -> None:
if isnan(self.lo) or isnan(self.hi):
raise ValueError("interval endpoints must not be NaN")
if self.lo > self.hi:
raise ValueError(f"empty interval: lo={self.lo!r} > hi={self.hi!r}")
# ----- constructors -------------------------------------------------- #
@classmethod
def point(cls, x: float) -> Interval:
"""Exact degenerate interval ``[x, x]`` for the float ``x`` itself.
No rounding is applied, so this is rigorous only when ``x`` is the
intended datum. To enclose a real that ``x`` merely approximates (e.g.
the rational ``1/10``), use :meth:`from_rational` instead.
"""
xf = float(x)
return cls(xf, xf)
@classmethod
def from_rational(cls, q: Fraction | int) -> Interval:
"""Tightest float interval enclosing an exact rational/integer ``q``."""
frac = Fraction(q)
f = float(frac)
lo = f
hi = f
as_frac = Fraction(f)
if as_frac > frac:
lo = _pred(f)
elif as_frac < frac:
hi = _succ(f)
return cls(lo, hi)
@classmethod
def from_value(cls, value: IntervalLike) -> Interval:
"""Promote any :data:`IntervalLike` to an :class:`Interval`.
``int`` / ``Fraction`` go through :meth:`from_rational` (tightest
outward-rounded enclosure of the exact rational); a ``float`` is
injected as an *exact point* ``[x, x]`` via :meth:`point` -- no
rounding, which is correct when the float is the literal datum (see the
class docstring for the rational-vs-float caveat).
"""
if isinstance(value, Interval):
return value
if isinstance(value, int | Fraction):
return cls.from_rational(value)
return cls.point(float(value))
@classmethod
def hull(cls, *values: IntervalLike) -> Interval:
"""Smallest interval containing every argument."""
if not values:
raise ValueError("hull requires at least one value")
ivs = [cls.from_value(v) for v in values]
return cls(min(iv.lo for iv in ivs), max(iv.hi for iv in ivs))
# ----- queries ------------------------------------------------------- #
@property
def mid(self) -> float:
"""A representable point near the midpoint (always inside the interval)."""
m = 0.5 * (self.lo + self.hi)
if m < self.lo:
return self.lo
if m > self.hi:
return self.hi
return m
@property
def rad(self) -> float:
"""An outward-rounded radius: ``hi - mid`` (>= true radius)."""
m = self.mid
return _succ(max(m - self.lo, self.hi - m))
@property
def width(self) -> float:
"""Outward-rounded width ``hi - lo``."""
return _succ(self.hi - self.lo)
@property
def mag(self) -> float:
"""Magnitude ``max |x|`` over the interval (outward rounded)."""
return _succ(max(abs(self.lo), abs(self.hi)))
@property
def mig(self) -> float:
"""Mignitude ``min |x|`` over the interval (0 if it straddles 0)."""
if self.lo <= 0.0 <= self.hi:
return 0.0
return _pred(min(abs(self.lo), abs(self.hi)))
def contains(self, x: float) -> bool:
return self.lo <= x <= self.hi
def contains_zero(self) -> bool:
return self.lo <= 0.0 <= self.hi
# ----- arithmetic ---------------------------------------------------- #
def __add__(self, other: IntervalLike) -> Interval:
o = Interval.from_value(other)
return Interval(_pred(self.lo + o.lo), _succ(self.hi + o.hi))
__radd__ = __add__
def __neg__(self) -> Interval:
return Interval(-self.hi, -self.lo)
def __sub__(self, other: IntervalLike) -> Interval:
o = Interval.from_value(other)
return Interval(_pred(self.lo - o.hi), _succ(self.hi - o.lo))
def __rsub__(self, other: IntervalLike) -> Interval:
return Interval.from_value(other).__sub__(self)
def __mul__(self, other: IntervalLike) -> Interval:
o = Interval.from_value(other)
products = (
self.lo * o.lo,
self.lo * o.hi,
self.hi * o.lo,
self.hi * o.hi,
)
return Interval(_pred(min(products)), _succ(max(products)))
__rmul__ = __mul__
def reciprocal(self) -> Interval:
"""``1 / self``; requires the interval to exclude zero."""
if self.contains_zero():
raise ZeroDivisionError("interval reciprocal requires 0 outside [lo, hi]")
return Interval(_pred(1.0 / self.hi), _succ(1.0 / self.lo))
def __truediv__(self, other: IntervalLike) -> Interval:
return self.__mul__(Interval.from_value(other).reciprocal())
def __rtruediv__(self, other: IntervalLike) -> Interval:
return Interval.from_value(other).__mul__(self.reciprocal())
def __pow__(self, n: int) -> Interval:
return self.pow_int(n)
def pow_int(self, n: int) -> Interval:
"""Rigorous integer power via interval binary exponentiation.
For an even ``n`` the base is first folded through :meth:`abs`, so a
sign-straddling interval yields the tight ``[0, mag**n]`` enclosure rather
than a loose one polluted by spurious negative corner products (``x**n`` is
non-negative for even ``n``). This only tightens the result; non-straddling
intervals are unaffected.
"""
if n < 0:
return self.pow_int(-n).reciprocal()
result = Interval.point(1.0)
base = self.abs() if n % 2 == 0 else self
e = n
while e > 0:
if e & 1:
result = result * base
e >>= 1
if e > 0:
base = base * base
return result
def abs(self) -> Interval:
"""Enclosure of ``|x|`` over the interval."""
if self.lo >= 0.0:
return self
if self.hi <= 0.0:
return -self
return Interval(0.0, _succ(max(-self.lo, self.hi)))
def sqrt(self) -> Interval:
"""Enclosure of ``sqrt(x)``; requires ``lo >= 0``.
``math.sqrt`` is an IEEE-754 *correctly rounded* operation (error
``<= 0.5 ulp``), so a single outward ``nextafter`` step per endpoint is a
rigorous bracket. This is unlike the libm transcendentals (``exp`` /
``log``), which are not guaranteed correctly rounded and therefore need the
wider :mod:`omnibias.core.verified.transcend` enclosures.
"""
from math import sqrt as _sqrt
if self.lo < 0.0:
raise ValueError("sqrt requires a non-negative interval")
return Interval(_pred(_sqrt(self.lo)), _succ(_sqrt(self.hi)))
def intersect(self, other: Interval) -> Interval:
lo = max(self.lo, other.lo)
hi = min(self.hi, other.hi)
if lo > hi:
raise ValueError("empty intersection")
return Interval(lo, hi)
def __repr__(self) -> str:
return f"Interval([{self.lo!r}, {self.hi!r}])"Other public import paths
omnibias.core.verified.Intervalomnibias.core.verified.interval.Interval
IntervalLike
omnibias.core.verified.IntervalLikeSource ↗IntervalLike = Union['Interval', int, float, Fraction]Anything that can be promoted to an Interval.
Read the implementation
IntervalLike = Union["Interval", int, float, Fraction]Other public import paths
omnibias.core.verified.IntervalLikeomnibias.core.verified.interval.IntervalLike
hull
omnibias.core.verified.hullSource ↗hull(values: list[IntervalLike]) -> IntervalFunctional alias for Interval.hull.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | list[IntervalLike]Required | See the operation contract and implementation below. |
IntervalExecuted regression · g2 non vacuous
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_g2_non_vacuous() -> None:
ex = worked_example()
assert float(ex["remainder_width"]) < 0.1
assert ex["vacuous"] is False
assert float(ex["width"]) < 0.1python -m pytest "packages/omnibias-core/tests/verified/test_tm_neuron.py::test_g2_non_vacuous" -qRead the implementation
def hull(values: list[IntervalLike]) -> Interval:
"""Functional alias for :meth:`Interval.hull`."""
return Interval.hull(*values)Other public import paths
omnibias.core.verified.hullomnibias.core.verified.interval.hull
sum_intervals
omnibias.core.verified.sum_intervalsSource ↗sum_intervals(values: list[Interval]) -> IntervalOutward-rounded sum of a list of intervals (left fold).
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | list[Interval]Required | See the operation contract and implementation below. |
IntervalExecuted regression · inf norm matrix upper bound
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_inf_norm_matrix_upper_bound() -> None:
a = to_interval_matrix([[1.0, -2.0], [3.0, 0.5]])
assert inf_norm_matrix(a) >= 3.5 # row sums 3, 3.5python -m pytest "packages/omnibias-core/tests/verified/test_numerics.py::test_inf_norm_matrix_upper_bound" -qRead the implementation
def sum_intervals(values: list[Interval]) -> Interval:
"""Outward-rounded sum of a list of intervals (left fold)."""
acc = Interval.point(0.0)
for v in values:
acc = acc + v
return accOther public import paths
omnibias.core.verified.sum_intervalsomnibias.core.verified.interval.sum_intervals