Skip to main content

omnibias.core.verified.interval

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.interval
Module 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 nextafter step would not cover the multi-rounding error of float.__pow__).
  • Division and reciprocal require the denominator interval to be bounded away from zero; otherwise ZeroDivisionError is 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.

CLASS

Interval​

omnibias.core.verified.IntervalSource ↗
class Interval

Dataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.

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 -- and 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.
  • point -- and 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.

Parameters

NameType & defaultContract
lodataclass fieldfloatRequiredSee the operation contract and implementation below.
hidataclass fieldfloatRequiredSee 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**-50
python -m pytest "packages/omnibias-core/tests/verified/test_interval.py::test_width_is_outward" -q
Regression 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 -q

Fields & methods

lofield
lo: float

Declared 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.hi
python -m pytest packages/omnibias-core/tests/test_certificate.py -k test_interval_roundtrip_is_bit_exact -q
View source ↗
hifield
hi: float

Declared 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.hi
python -m pytest packages/omnibias-core/tests/test_certificate.py -k test_interval_roundtrip_is_bit_exact -q
View source ↗
__post_init__method
__post_init__(self) -> None

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

Returns: None

Validation & failure cases
  • When isnan(self.lo) or isnan(self.hi), raises ValueError('interval endpoints must not be NaN').
  • When self.lo > self.hi, raises ValueError(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**-50
python -m pytest "packages/omnibias-core/tests/verified/test_interval.py::test_width_is_outward" -q
Method 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}")
View source ↗
pointmethod
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 from_rational instead.

Parameters

NameType & defaultContract
xpositional-or-keywordfloatRequiredSee 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]" -q
Method 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)
View source ↗
from_rationalmethod
from_rational(cls, q: Fraction | int) -> Interval

Tightest float interval enclosing an exact rational/integer q.

Parameters

NameType & defaultContract
qpositional-or-keywordFraction | intRequiredSee 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]" -q
Method 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)
View source ↗
from_valuemethod
from_value(cls, value: IntervalLike) -> Interval

Promote 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

NameType & defaultContract
valuepositional-or-keywordIntervalLikeRequiredSee 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]" -q
Method 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))
View source ↗
hullmethod
hull(cls, *values: IntervalLike) -> Interval

Smallest interval containing every argument.

Parameters

NameType & defaultContract
valuesvariadic positionalIntervalLikeRequiredSee the operation contract and implementation below.

Returns: Interval

Validation & failure cases
  • When not values, raises ValueError('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.1
python -m pytest "packages/omnibias-core/tests/verified/test_tm_neuron.py::test_g2_non_vacuous" -q
Method 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))
View source ↗
midproperty
mid(self) -> float

A 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-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Method 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 m
View source ↗
radproperty
rad(self) -> float

An 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-15
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_constant_is_tight" -q
Method 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))
View source ↗
widthproperty
width(self) -> float

Outward-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**-50
python -m pytest "packages/omnibias-core/tests/verified/test_interval.py::test_width_is_outward" -q
Method implementation
    def width(self) -> float:
        """Outward-rounded width ``hi - lo``."""
        return _succ(self.hi - self.lo)
View source ↗
magproperty
mag(self) -> float

Magnitude 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-300
python -m pytest "packages/omnibias-core/tests/test_verified_pde_certificate.py::test_boundary_residual_empty_is_zero" -q
Method implementation
    def mag(self) -> float:
        """Magnitude ``max |x|`` over the interval (outward rounded)."""
        return _succ(max(abs(self.lo), abs(self.hi)))
View source ↗
migproperty
mig(self) -> float

Mignitude 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.0
python -m pytest "packages/omnibias-core/tests/test_verified_complex_interval.py::test_modulus_lower_bound_zero_when_straddling_origin" -q
Method 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)))
View source ↗
containsmethod
contains(self, x: float) -> bool

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

Parameters

NameType & defaultContract
xpositional-or-keywordfloatRequiredSee 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]" -q
Method implementation
    def contains(self, x: float) -> bool:
        return self.lo <= x <= self.hi
View source ↗
contains_zeromethod
contains_zero(self) -> bool

See 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]" -q
Method implementation
    def contains_zero(self) -> bool:
        return self.lo <= 0.0 <= self.hi
View source ↗
__add__method
__add__(self, other: IntervalLike) -> Interval

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalLikeRequiredSee 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]" -q
Method implementation
    def __add__(self, other: IntervalLike) -> Interval:
        o = Interval.from_value(other)
        return Interval(_pred(self.lo + o.lo), _succ(self.hi + o.hi))
View source ↗
__neg__method
__neg__(self) -> Interval

See 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]" -q
Method implementation
    def __neg__(self) -> Interval:
        return Interval(-self.hi, -self.lo)
View source ↗
__sub__method
__sub__(self, other: IntervalLike) -> Interval

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalLikeRequiredSee 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.certified
python -m pytest "packages/omnibias-struct/tests/test_decode.py::test_dag_large_ball_not_certified" -q
Method implementation
    def __sub__(self, other: IntervalLike) -> Interval:
        o = Interval.from_value(other)
        return Interval(_pred(self.lo - o.hi), _succ(self.hi - o.lo))
View source ↗
__rsub__method
__rsub__(self, other: IntervalLike) -> Interval

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalLikeRequiredSee 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 truth
python -m pytest "packages/omnibias-core/tests/verified/test_affine.py::test_interval_loses_the_correlation" -q
Method implementation
    def __rsub__(self, other: IntervalLike) -> Interval:
        return Interval.from_value(other).__sub__(self)
View source ↗
__mul__method
__mul__(self, other: IntervalLike) -> Interval

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalLikeRequiredSee 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]" -q
Method 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)))
View source ↗
reciprocalmethod
reciprocal(self) -> Interval

1 / self; requires the interval to exclude zero.

Returns: Interval

Validation & failure cases
  • When self.contains_zero(), raises ZeroDivisionError('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]" -q
Method 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))
View source ↗
__truediv__method
__truediv__(self, other: IntervalLike) -> Interval

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalLikeRequiredSee 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-12
python -m pytest "packages/omnibias-core/tests/test_verified_radii_spectral.py::test_manufactured_solution_is_an_exact_zero" -q
Method implementation
    def __truediv__(self, other: IntervalLike) -> Interval:
        return self.__mul__(Interval.from_value(other).reciprocal())
View source ↗
__rtruediv__method
__rtruediv__(self, other: IntervalLike) -> Interval

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

Parameters

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

Returns: Interval

Method implementation
    def __rtruediv__(self, other: IntervalLike) -> Interval:
        return Interval.from_value(other).__mul__(self.reciprocal())
View source ↗
__pow__method
__pow__(self, n: int) -> Interval

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

Parameters

NameType & defaultContract
npositional-or-keywordintRequiredSee 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]" -q
Method implementation
    def __pow__(self, n: int) -> Interval:
        return self.pow_int(n)
View source ↗
pow_intmethod
pow_int(self, n: int) -> Interval

Rigorous 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

NameType & defaultContract
npositional-or-keywordintRequiredSee 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]" -q
Method 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 result
View source ↗
absmethod
abs(self) -> Interval

Enclosure 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]" -q
Method 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)))
View source ↗
sqrtmethod
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 omnibias.core.verified.transcend enclosures.

Returns: Interval

Validation & failure cases
  • When self.lo < 0.0, raises ValueError('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" -q
Method 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)))
View source ↗
intersectmethod
intersect(self, other: Interval) -> Interval

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

Parameters

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

Returns: Interval

Validation & failure cases
  • When lo > hi, raises ValueError('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" -q
Method 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)
View source ↗
__repr__method
__repr__(self) -> str

See 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 text
python -m pytest "packages/omnibias-core/tests/verified/test_hermite_basis.py::test_hermite_expansion_repr" -q
Method implementation
    def __repr__(self) -> str:
        return f"Interval([{self.lo!r}, {self.hi!r}])"
View source ↗
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.Interval
  • omnibias.core.verified.interval.Interval
CONSTANT

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.IntervalLike
  • omnibias.core.verified.interval.IntervalLike
FUNCTION

hull​

omnibias.core.verified.hullSource ↗
hull(values: list[IntervalLike]) -> Interval

Functional alias for Interval.hull.

Parameters

NameType & defaultContract
valuespositional-or-keywordlist[IntervalLike]RequiredSee the operation contract and implementation below.
ReturnsInterval
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.1
python -m pytest "packages/omnibias-core/tests/verified/test_tm_neuron.py::test_g2_non_vacuous" -q
Read 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.hull
  • omnibias.core.verified.interval.hull
FUNCTION

sum_intervals​

omnibias.core.verified.sum_intervalsSource ↗
sum_intervals(values: list[Interval]) -> Interval

Outward-rounded sum of a list of intervals (left fold).

Parameters

NameType & defaultContract
valuespositional-or-keywordlist[Interval]RequiredSee the operation contract and implementation below.
ReturnsInterval
Executed 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.5
python -m pytest "packages/omnibias-core/tests/verified/test_numerics.py::test_inf_norm_matrix_upper_bound" -q
Read 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 acc
Other public import paths
  • omnibias.core.verified.sum_intervals
  • omnibias.core.verified.interval.sum_intervals