Skip to main content

omnibias.core.verified.interval_array

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

Vectorized outward-rounded interval arithmetic.

IntervalArray stores lower and upper binary64 endpoint arrays separately. Each elementary operation is rounded one representable step outwards with numpy.nextafter. Consequently it encloses the elementwise real operation for all values in the input boxes, under the same IEEE-754 assumptions as omnibias.core.verified.interval.

The type is deliberately a small dense-array substrate rather than a replacement for a sparse package. sparse_matvec accepts COO entries so rigorous Gram and residual operators can avoid materialising a dense matrix while keeping the accumulation order explicitly outward rounded.

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.

CONSTANT

BoolArray​

omnibias.core.verified.interval_array.BoolArraySource ↗
BoolArray: TypeAlias = NDArray[np.bool_]

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
BoolArray: TypeAlias = NDArray[np.bool_]
CONSTANT

FloatArray​

omnibias.core.verified.interval_array.FloatArraySource ↗
FloatArray: TypeAlias = NDArray[np.float64]

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
FloatArray: TypeAlias = NDArray[np.float64]
CLASS

IntervalArray​

omnibias.core.verified.IntervalArraySource ↗
class IntervalArray

A shape-preserving array of closed real intervals.

The constructor accepts matching or broadcastable lower and upper endpoint arrays. It does not round those endpoints; callers must provide values that already enclose the intended reals. point is appropriate when a binary64 array is the literal input datum.

Parameters

NameType & defaultContract
lopositional-or-keywordArrayLikeRequiredSee the operation contract and implementation below.
hipositional-or-keywordArrayLikeRequiredSee the operation contract and implementation below.
Executed regression · wide box around a definite matrix loses definiteness

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_wide_box_around_a_definite_matrix_loses_definiteness() -> None:
    """Widening a certified box eventually returns an honest inconclusive."""
    center = np.array([[1.0, 0.0], [0.0, 1.0]])
    assert is_positive_definite_array(_symmetric_box(center, 0.25)) is True
    assert is_positive_definite_array(_symmetric_box(center, 4.0)) is False
python -m pytest "packages/omnibias-core/tests/verified/test_linalg_array.py::test_wide_box_around_a_definite_matrix_loses_definiteness" -q
Regression example · straddling pivot is reported as uncertified

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_straddling_pivot_is_reported_as_uncertified() -> None:
    """A box that contains a singular matrix cannot certify an inertia."""
    box = IntervalArray([[-0.5, 1.0], [1.0, 3.0]], [[0.5, 1.0], [1.0, 3.0]])
    assert interval_ldlt_inertia_array(box) is None
    assert interval_ldlt_pivots_array(box) is None
    assert interval_ldlt_factor_array(box) is None
    assert is_positive_definite_array(box) is False
    assert interval_ldlt_inertia(_scalar_matrix(box)) is None
python -m pytest packages/omnibias-core/tests/verified/test_linalg_array.py -k test_straddling_pivot_is_reported_as_uncertified -q

Fields & methods

lofield
lo: FloatArray

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

Regression example · deterministic boxes match scalar reference and numpy

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_deterministic_boxes_match_scalar_reference_and_numpy(
    midpoint: list[list[float]], radius: float
) -> None:
    """Named matrices: parity with the scalar path plus a true-spectrum check."""
    center = np.asarray(midpoint, dtype=np.float64)
    box = _symmetric_box(center, radius)
    _assert_matches_scalar_reference(box)

    # A dense deterministic interior grid, symmetrized on the lower triangle.
    samples = [
        _symmetrize_lower(box.lo + fraction * (box.hi - box.lo))
        for fraction in np.linspace(0.0, 1.0, 9)
    ]
    _assert_matches_numpy_spectrum(box, [np.clip(s, box.lo, box.hi) for s in samples])
python -m pytest packages/omnibias-core/tests/verified/test_linalg_array.py -k test_deterministic_boxes_match_scalar_reference_and_numpy -q
View source ↗
hifield
hi: FloatArray

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

Regression example · deterministic boxes match scalar reference and numpy

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_deterministic_boxes_match_scalar_reference_and_numpy(
    midpoint: list[list[float]], radius: float
) -> None:
    """Named matrices: parity with the scalar path plus a true-spectrum check."""
    center = np.asarray(midpoint, dtype=np.float64)
    box = _symmetric_box(center, radius)
    _assert_matches_scalar_reference(box)

    # A dense deterministic interior grid, symmetrized on the lower triangle.
    samples = [
        _symmetrize_lower(box.lo + fraction * (box.hi - box.lo))
        for fraction in np.linspace(0.0, 1.0, 9)
    ]
    _assert_matches_numpy_spectrum(box, [np.clip(s, box.lo, box.hi) for s in samples])
python -m pytest packages/omnibias-core/tests/verified/test_linalg_array.py -k test_deterministic_boxes_match_scalar_reference_and_numpy -q
View source ↗
__init__method
__init__(self, lo: ArrayLike, hi: ArrayLike) -> None

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

Parameters

NameType & defaultContract
lopositional-or-keywordArrayLikeRequiredSee the operation contract and implementation below.
hipositional-or-keywordArrayLikeRequiredSee the operation contract and implementation below.

Returns: None

Validation & failure cases
  • When bool(np.any(np.isnan(lo_out))) or bool(np.any(np.isnan(hi_out))), raises ValueError('interval endpoints must not be NaN').
  • When bool(np.any(lo_out > hi_out)), raises ValueError('interval lower endpoint exceeds upper endpoint').
Executed regression · wide box around a definite matrix loses definiteness

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_wide_box_around_a_definite_matrix_loses_definiteness() -> None:
    """Widening a certified box eventually returns an honest inconclusive."""
    center = np.array([[1.0, 0.0], [0.0, 1.0]])
    assert is_positive_definite_array(_symmetric_box(center, 0.25)) is True
    assert is_positive_definite_array(_symmetric_box(center, 4.0)) is False
python -m pytest "packages/omnibias-core/tests/verified/test_linalg_array.py::test_wide_box_around_a_definite_matrix_loses_definiteness" -q
Method implementation
    def __init__(self, lo: ArrayLike, hi: ArrayLike) -> None:
        lo_raw = _as_float_array(lo)
        hi_raw = _as_float_array(hi)
        try:
            lo_arr, hi_arr = np.broadcast_arrays(lo_raw, hi_raw)
        except ValueError as exc:
            raise ValueError("interval endpoint shapes are not broadcastable") from exc
        lo_out = cast(FloatArray, np.array(lo_arr, dtype=np.float64, copy=True))
        hi_out = cast(FloatArray, np.array(hi_arr, dtype=np.float64, copy=True))
        if bool(np.any(np.isnan(lo_out))) or bool(np.any(np.isnan(hi_out))):
            raise ValueError("interval endpoints must not be NaN")
        if bool(np.any(lo_out > hi_out)):
            raise ValueError("interval lower endpoint exceeds upper endpoint")
        lo_out.setflags(write=False)
        hi_out.setflags(write=False)
        object.__setattr__(self, "lo", lo_out)
        object.__setattr__(self, "hi", hi_out)
View source ↗
pointmethod
point(cls, value: ArrayLike) -> IntervalArray

Exact point intervals for binary64 input data.

Parameters

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

Returns: IntervalArray

Executed regression · domain errors

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_domain_errors() -> None:
    with pytest.raises(ValueError, match="two-dimensional"):
        interval_ldlt_inertia_array(IntervalArray.point([1.0, 2.0]))
    with pytest.raises(ValueError, match="non-empty square"):
        interval_ldlt_inertia_array(IntervalArray.point([[1.0, 2.0]]))
    with pytest.raises(ValueError, match="non-empty square"):
        interval_ldlt_pivots_array(IntervalArray.point(np.zeros((0, 0))))
    with pytest.raises(ValueError, match="two-dimensional"):
        interval_ldlt_factor_array(IntervalArray.point(np.zeros((2, 2, 2))))
python -m pytest "packages/omnibias-core/tests/verified/test_linalg_array.py::test_domain_errors" -q
Method implementation
    def point(cls, value: ArrayLike) -> IntervalArray:
        """Exact point intervals for binary64 input data."""
        values = _as_float_array(value)
        return cls(values, values)
View source ↗
from_valuemethod
from_value(cls, value: IntervalArray | Interval | ArrayLike) -> IntervalArray

Promote interval or scalar/array data to an interval array.

Parameters

NameType & defaultContract
valuepositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Executed regression · wide box around a definite matrix loses definiteness

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_wide_box_around_a_definite_matrix_loses_definiteness() -> None:
    """Widening a certified box eventually returns an honest inconclusive."""
    center = np.array([[1.0, 0.0], [0.0, 1.0]])
    assert is_positive_definite_array(_symmetric_box(center, 0.25)) is True
    assert is_positive_definite_array(_symmetric_box(center, 4.0)) is False
python -m pytest "packages/omnibias-core/tests/verified/test_linalg_array.py::test_wide_box_around_a_definite_matrix_loses_definiteness" -q
Method implementation
    def from_value(cls, value: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Promote interval or scalar/array data to an interval array."""
        if isinstance(value, IntervalArray):
            return value
        if isinstance(value, Interval):
            return cls(np.asarray(value.lo), np.asarray(value.hi))
        return cls.point(value)
View source ↗
from_intervalsmethod
from_intervals(cls, values: ArrayLike) -> IntervalArray

Build a one-dimensional interval array from scalar Intervals.

Parameters

NameType & defaultContract
valuespositional-or-keywordArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Validation & failure cases
  • When raw.ndim != 1, raises ValueError('from_intervals requires a one-dimensional sequence').
  • When not all((isinstance(value, Interval) for value in raw)), raises TypeError('from_intervals requires only Interval values').
Method implementation
    def from_intervals(cls, values: ArrayLike) -> IntervalArray:
        """Build a one-dimensional interval array from scalar :class:`Interval`s."""
        raw = np.asarray(values, dtype=object)
        if raw.ndim != 1:
            raise ValueError("from_intervals requires a one-dimensional sequence")
        if not all(isinstance(value, Interval) for value in raw):
            raise TypeError("from_intervals requires only Interval values")
        return cls(
            np.asarray([value.lo for value in raw], dtype=np.float64),
            np.asarray([value.hi for value in raw], dtype=np.float64),
        )
View source ↗
hullmethod
hull(cls, *values: IntervalArray | Interval | ArrayLike) -> IntervalArray

Smallest elementwise interval array containing every supplied input.

Parameters

NameType & defaultContract
valuesvariadic positionalIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Validation & failure cases
  • When not values, raises ValueError('hull requires at least one value').
Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def hull(cls, *values: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Smallest elementwise interval array containing every supplied input."""
        if not values:
            raise ValueError("hull requires at least one value")
        intervals = [cls.from_value(value) for value in values]
        try:
            lows = np.broadcast_arrays(*(interval.lo for interval in intervals))
            highs = np.broadcast_arrays(*(interval.hi for interval in intervals))
        except ValueError as exc:
            raise ValueError("hull inputs are not broadcastable") from exc
        return cls(
            cast(FloatArray, np.min(np.stack(lows), axis=0)),
            cast(FloatArray, np.max(np.stack(highs), axis=0)),
        )
View source ↗
shapeproperty
shape(self) -> tuple[int, ...]

The common endpoint shape.

Returns: tuple[int, ...]

Executed regression · wide box around a definite matrix loses definiteness

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_wide_box_around_a_definite_matrix_loses_definiteness() -> None:
    """Widening a certified box eventually returns an honest inconclusive."""
    center = np.array([[1.0, 0.0], [0.0, 1.0]])
    assert is_positive_definite_array(_symmetric_box(center, 0.25)) is True
    assert is_positive_definite_array(_symmetric_box(center, 4.0)) is False
python -m pytest "packages/omnibias-core/tests/verified/test_linalg_array.py::test_wide_box_around_a_definite_matrix_loses_definiteness" -q
Method implementation
    def shape(self) -> tuple[int, ...]:
        """The common endpoint shape."""
        return self.lo.shape
View source ↗
ndimproperty
ndim(self) -> int

Number of array dimensions.

Returns: int

Executed regression · wide box around a definite matrix loses definiteness

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_wide_box_around_a_definite_matrix_loses_definiteness() -> None:
    """Widening a certified box eventually returns an honest inconclusive."""
    center = np.array([[1.0, 0.0], [0.0, 1.0]])
    assert is_positive_definite_array(_symmetric_box(center, 0.25)) is True
    assert is_positive_definite_array(_symmetric_box(center, 4.0)) is False
python -m pytest "packages/omnibias-core/tests/verified/test_linalg_array.py::test_wide_box_around_a_definite_matrix_loses_definiteness" -q
Method implementation
    def ndim(self) -> int:
        """Number of array dimensions."""
        return self.lo.ndim
View source ↗
sizeproperty
size(self) -> int

Total number of scalar intervals.

Returns: int

Method implementation
    def size(self) -> int:
        """Total number of scalar intervals."""
        return self.lo.size
View source ↗
midproperty
mid(self) -> FloatArray

A representable midpoint array contained in each interval.

Returns: FloatArray

Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def mid(self) -> FloatArray:
        """A representable midpoint array contained in each interval."""
        midpoint = 0.5 * self.lo + 0.5 * self.hi
        midpoint = cast(
            FloatArray,
            np.where(np.isneginf(self.lo) & np.isposinf(self.hi), 0.0, midpoint),
        )
        midpoint = cast(FloatArray, np.maximum(self.lo, midpoint))
        return cast(FloatArray, np.minimum(self.hi, midpoint))
View source ↗
radproperty
rad(self) -> FloatArray

Outward-rounded radius array.

Returns: FloatArray

Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def rad(self) -> FloatArray:
        """Outward-rounded radius array."""
        midpoint = self.mid
        return _succ(cast(FloatArray, np.maximum(midpoint - self.lo, self.hi - midpoint)))
View source ↗
widthproperty
width(self) -> FloatArray

Outward-rounded widths.

Returns: FloatArray

Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def width(self) -> FloatArray:
        """Outward-rounded widths."""
        return _succ(self.hi - self.lo)
View source ↗
magproperty
mag(self) -> FloatArray

Outward-rounded elementwise magnitude bounds.

Returns: FloatArray

Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def mag(self) -> FloatArray:
        """Outward-rounded elementwise magnitude bounds."""
        return _succ(cast(FloatArray, np.maximum(np.abs(self.lo), np.abs(self.hi))))
View source ↗
migproperty
mig(self) -> FloatArray

Outward-rounded elementwise mignitudes.

Returns: FloatArray

Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def mig(self) -> FloatArray:
        """Outward-rounded elementwise mignitudes."""
        straddles_zero = (self.lo <= 0.0) & (0.0 <= self.hi)
        nonzero = _pred(cast(FloatArray, np.minimum(np.abs(self.lo), np.abs(self.hi))))
        return cast(FloatArray, np.where(straddles_zero, 0.0, nonzero))
View source ↗
containsmethod
contains(self, value: ArrayLike) -> BoolArray

Elementwise containment test, with NumPy broadcasting.

Parameters

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

Returns: BoolArray

Executed regression · deterministic boxes match scalar reference and numpy

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_deterministic_boxes_match_scalar_reference_and_numpy(
    midpoint: list[list[float]], radius: float
) -> None:
    """Named matrices: parity with the scalar path plus a true-spectrum check."""
    center = np.asarray(midpoint, dtype=np.float64)
    box = _symmetric_box(center, radius)
    _assert_matches_scalar_reference(box)

    # A dense deterministic interior grid, symmetrized on the lower triangle.
    samples = [
        _symmetrize_lower(box.lo + fraction * (box.hi - box.lo))
        for fraction in np.linspace(0.0, 1.0, 9)
    ]
    _assert_matches_numpy_spectrum(box, [np.clip(s, box.lo, box.hi) for s in samples])
python -m pytest "packages/omnibias-core/tests/verified/test_linalg_array.py::test_deterministic_boxes_match_scalar_reference_and_numpy[0.0-diagonal_indefinite]" -q
Method implementation
    def contains(self, value: ArrayLike) -> BoolArray:
        """Elementwise containment test, with NumPy broadcasting."""
        values = _as_float_array(value)
        try:
            lo, hi, points = np.broadcast_arrays(self.lo, self.hi, values)
        except ValueError as exc:
            raise ValueError("containment value is not broadcastable") from exc
        return (lo <= points) & (points <= hi)
View source ↗
contains_zeromethod
contains_zero(self) -> BoolArray

Elementwise test for whether zero belongs to each interval.

Returns: BoolArray

Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def contains_zero(self) -> BoolArray:
        """Elementwise test for whether zero belongs to each interval."""
        return (self.lo <= 0.0) & (0.0 <= self.hi)
View source ↗
__add__method
__add__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Executed regression · elementwise operations enclose grid and random samples

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_elementwise_operations_enclose_grid_and_random_samples() -> None:
    """All scalar operations remain sound in the vectorized representation."""
    left = IntervalArray(
        [[-1.5, 0.25, 2.0], [-0.8, -3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, -0.4, 2.2]],
    )
    right = IntervalArray(
        [[0.2, 1.1, 0.5], [0.7, 0.25, 1.5]],
        [[1.4, 2.3, 1.8], [1.9, 0.75, 3.0]],
    )
    positive = IntervalArray(
        [[0.0, 0.25, 2.0], [0.8, 3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, 4.0, 2.2]],
    )

    summed = left + right
    differenced = left - right
    multiplied = left * right
    divided = left / right
    squared = left.pow_int(2)
    cubed = left.pow_int(3)
    absolute = left.abs()
    rooted = positive.sqrt()
    reciprocal = right.reciprocal()
    _assert_encloses_scalar(summed, lambda x, y: x + y, left, right)
    _assert_encloses_scalar(differenced, lambda x, y: x - y, left, right)
    _assert_encloses_scalar(multiplied, lambda x, y: x * y, left, right)
    _assert_encloses_scalar(divided, lambda x, y: x / y, left, right)
    for index in np.ndindex(left.shape):
        scalar = _scalar_at(left, index)
        scalar_positive = _scalar_at(positive, index)
        scalar_right = _scalar_at(right, index)
        assert squared.lo[index] <= scalar.pow_int(2).lo <= scalar.pow_int(2).hi <= squared.hi[index]
        assert cubed.lo[index] <= scalar.pow_int(3).lo <= scalar.pow_int(3).hi <= cubed.hi[index]
        assert absolute.lo[index] <= scalar.abs().lo <= scalar.abs().hi <= absolute.hi[index]
        assert rooted.lo[index] <= scalar_positive.sqrt().lo <= scalar_positive.sqrt().hi <= rooted.hi[index]
        assert (
            reciprocal.lo[index]
            <= scalar_right.reciprocal().lo
            <= scalar_right.reciprocal().hi
            <= reciprocal.hi[index]
        )

    # Dense deterministic interior grid.
    for left_t in np.linspace(0.0, 1.0, 17):
        sample_left = _grid_sample(left, float(left_t))
        for right_t in np.linspace(0.0, 1.0, 17):
            sample_right = _grid_sample(right, float(right_t))
            assert np.all(summed.contains(sample_left + sample_right))
            assert np.all(differenced.contains(sample_left - sample_right))
            assert np.all(multiplied.contains(sample_left * sample_right))
            assert np.all(divided.contains(sample_left / sample_right))
            assert np.all(reciprocal.contains(1.0 / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        sample_positive = _grid_sample(positive, float(left_t))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))

    # Independent random samples exercise distinct values in every array entry.
    rng = np.random.default_rng(20260827)
    for _ in range(128):
        sample_left = rng.uniform(left.lo, left.hi)
        sample_right = rng.uniform(right.lo, right.hi)
        sample_positive = rng.uniform(positive.lo, positive.hi)
        assert np.all(summed.contains(sample_left + sample_right))
        assert np.all(differenced.contains(sample_left - sample_right))
        assert np.all(multiplied.contains(sample_left * sample_right))
        assert np.all(divided.contains(sample_left / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))
        assert np.all(reciprocal.contains(1.0 / sample_right))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_elementwise_operations_enclose_grid_and_random_samples" -q
Method implementation
    def __add__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        return IntervalArray(_pred(left_lo + right_lo), _succ(left_hi + right_hi))
View source ↗
__neg__method
__neg__(self) -> IntervalArray

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

Returns: IntervalArray

Method implementation
    def __neg__(self) -> IntervalArray:
        return IntervalArray(-self.hi, -self.lo)
View source ↗
__sub__method
__sub__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Executed regression · elementwise operations enclose grid and random samples

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_elementwise_operations_enclose_grid_and_random_samples() -> None:
    """All scalar operations remain sound in the vectorized representation."""
    left = IntervalArray(
        [[-1.5, 0.25, 2.0], [-0.8, -3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, -0.4, 2.2]],
    )
    right = IntervalArray(
        [[0.2, 1.1, 0.5], [0.7, 0.25, 1.5]],
        [[1.4, 2.3, 1.8], [1.9, 0.75, 3.0]],
    )
    positive = IntervalArray(
        [[0.0, 0.25, 2.0], [0.8, 3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, 4.0, 2.2]],
    )

    summed = left + right
    differenced = left - right
    multiplied = left * right
    divided = left / right
    squared = left.pow_int(2)
    cubed = left.pow_int(3)
    absolute = left.abs()
    rooted = positive.sqrt()
    reciprocal = right.reciprocal()
    _assert_encloses_scalar(summed, lambda x, y: x + y, left, right)
    _assert_encloses_scalar(differenced, lambda x, y: x - y, left, right)
    _assert_encloses_scalar(multiplied, lambda x, y: x * y, left, right)
    _assert_encloses_scalar(divided, lambda x, y: x / y, left, right)
    for index in np.ndindex(left.shape):
        scalar = _scalar_at(left, index)
        scalar_positive = _scalar_at(positive, index)
        scalar_right = _scalar_at(right, index)
        assert squared.lo[index] <= scalar.pow_int(2).lo <= scalar.pow_int(2).hi <= squared.hi[index]
        assert cubed.lo[index] <= scalar.pow_int(3).lo <= scalar.pow_int(3).hi <= cubed.hi[index]
        assert absolute.lo[index] <= scalar.abs().lo <= scalar.abs().hi <= absolute.hi[index]
        assert rooted.lo[index] <= scalar_positive.sqrt().lo <= scalar_positive.sqrt().hi <= rooted.hi[index]
        assert (
            reciprocal.lo[index]
            <= scalar_right.reciprocal().lo
            <= scalar_right.reciprocal().hi
            <= reciprocal.hi[index]
        )

    # Dense deterministic interior grid.
    for left_t in np.linspace(0.0, 1.0, 17):
        sample_left = _grid_sample(left, float(left_t))
        for right_t in np.linspace(0.0, 1.0, 17):
            sample_right = _grid_sample(right, float(right_t))
            assert np.all(summed.contains(sample_left + sample_right))
            assert np.all(differenced.contains(sample_left - sample_right))
            assert np.all(multiplied.contains(sample_left * sample_right))
            assert np.all(divided.contains(sample_left / sample_right))
            assert np.all(reciprocal.contains(1.0 / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        sample_positive = _grid_sample(positive, float(left_t))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))

    # Independent random samples exercise distinct values in every array entry.
    rng = np.random.default_rng(20260827)
    for _ in range(128):
        sample_left = rng.uniform(left.lo, left.hi)
        sample_right = rng.uniform(right.lo, right.hi)
        sample_positive = rng.uniform(positive.lo, positive.hi)
        assert np.all(summed.contains(sample_left + sample_right))
        assert np.all(differenced.contains(sample_left - sample_right))
        assert np.all(multiplied.contains(sample_left * sample_right))
        assert np.all(divided.contains(sample_left / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))
        assert np.all(reciprocal.contains(1.0 / sample_right))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_elementwise_operations_enclose_grid_and_random_samples" -q
Method implementation
    def __sub__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        return IntervalArray(_pred(left_lo - right_hi), _succ(left_hi - right_lo))
View source ↗
__rsub__method
__rsub__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Method implementation
    def __rsub__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        return self.from_value(other).__sub__(self)
View source ↗
__mul__method
__mul__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Executed regression · dense and sparse matvec and dot are sound

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_dense_and_sparse_matvec_and_dot_are_sound() -> None:
    """Products use outward accumulation and agree componentwise with Interval."""
    matrix = IntervalArray(
        [[0.5, -1.3, 0.2], [1.1, -0.7, 0.4]],
        [[1.2, -0.3, 0.9], [1.8, 0.2, 1.1]],
    )
    vector = IntervalArray([-0.8, 0.5, 1.2], [0.6, 1.5, 2.0])
    dense = matrix.matvec(vector)
    rows = np.asarray([0, 0, 0, 1, 1, 1])
    columns = np.asarray([0, 1, 2, 0, 1, 2])
    entries = IntervalArray(matrix.lo[rows, columns], matrix.hi[rows, columns])
    sparse = sparse_matvec(rows, columns, entries, vector, matrix.shape)
    dot = vector.dot(vector)

    for row in range(matrix.shape[0]):
        scalar_sum = Interval.point(0.0)
        for column in range(matrix.shape[1]):
            scalar_sum = scalar_sum + _scalar_at(matrix, (row, column)) * _scalar_at(
                vector, (column,)
            )
        assert dense.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= dense.hi[row]
        assert sparse.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= sparse.hi[row]
    scalar_dot = Interval.point(0.0)
    for value in range(vector.shape[0]):
        scalar_dot = scalar_dot + _scalar_at(vector, (value,)) * _scalar_at(vector, (value,))
    assert dot.lo <= scalar_dot.lo <= scalar_dot.hi <= dot.hi

    # Dense deterministic samples and independent random samples.
    rng = np.random.default_rng(20260827)
    samples = [
        (
            _grid_sample(matrix, float(t)),
            _grid_sample(vector, float(1.0 - t)),
        )
        for t in np.linspace(0.0, 1.0, 17)
    ]
    samples.extend(
        (rng.uniform(matrix.lo, matrix.hi), rng.uniform(vector.lo, vector.hi))
        for _ in range(128)
    )
    for matrix_sample, vector_sample in samples:
        expected = matrix_sample @ vector_sample
        assert np.all(dense.contains(expected))
        assert np.all(sparse.contains(expected))
        assert dot.contains(float(vector_sample @ vector_sample))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_dense_and_sparse_matvec_and_dot_are_sound" -q
Method implementation
    def __mul__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        lo, hi = _mul_bounds(left_lo, left_hi, right_lo, right_hi)
        return IntervalArray(lo, hi)
View source ↗
reciprocalmethod
reciprocal(self) -> IntervalArray

Elementwise reciprocal; every entry must exclude zero.

Returns: IntervalArray

Validation & failure cases
  • When bool(np.any(self.contains_zero())), raises ZeroDivisionError('interval reciprocal requires zero outside every interval').
Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def reciprocal(self) -> IntervalArray:
        """Elementwise reciprocal; every entry must exclude zero."""
        if bool(np.any(self.contains_zero())):
            raise ZeroDivisionError("interval reciprocal requires zero outside every interval")
        return IntervalArray(_pred(1.0 / self.hi), _succ(1.0 / self.lo))
View source ↗
__truediv__method
__truediv__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Executed regression · elementwise operations enclose grid and random samples

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_elementwise_operations_enclose_grid_and_random_samples() -> None:
    """All scalar operations remain sound in the vectorized representation."""
    left = IntervalArray(
        [[-1.5, 0.25, 2.0], [-0.8, -3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, -0.4, 2.2]],
    )
    right = IntervalArray(
        [[0.2, 1.1, 0.5], [0.7, 0.25, 1.5]],
        [[1.4, 2.3, 1.8], [1.9, 0.75, 3.0]],
    )
    positive = IntervalArray(
        [[0.0, 0.25, 2.0], [0.8, 3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, 4.0, 2.2]],
    )

    summed = left + right
    differenced = left - right
    multiplied = left * right
    divided = left / right
    squared = left.pow_int(2)
    cubed = left.pow_int(3)
    absolute = left.abs()
    rooted = positive.sqrt()
    reciprocal = right.reciprocal()
    _assert_encloses_scalar(summed, lambda x, y: x + y, left, right)
    _assert_encloses_scalar(differenced, lambda x, y: x - y, left, right)
    _assert_encloses_scalar(multiplied, lambda x, y: x * y, left, right)
    _assert_encloses_scalar(divided, lambda x, y: x / y, left, right)
    for index in np.ndindex(left.shape):
        scalar = _scalar_at(left, index)
        scalar_positive = _scalar_at(positive, index)
        scalar_right = _scalar_at(right, index)
        assert squared.lo[index] <= scalar.pow_int(2).lo <= scalar.pow_int(2).hi <= squared.hi[index]
        assert cubed.lo[index] <= scalar.pow_int(3).lo <= scalar.pow_int(3).hi <= cubed.hi[index]
        assert absolute.lo[index] <= scalar.abs().lo <= scalar.abs().hi <= absolute.hi[index]
        assert rooted.lo[index] <= scalar_positive.sqrt().lo <= scalar_positive.sqrt().hi <= rooted.hi[index]
        assert (
            reciprocal.lo[index]
            <= scalar_right.reciprocal().lo
            <= scalar_right.reciprocal().hi
            <= reciprocal.hi[index]
        )

    # Dense deterministic interior grid.
    for left_t in np.linspace(0.0, 1.0, 17):
        sample_left = _grid_sample(left, float(left_t))
        for right_t in np.linspace(0.0, 1.0, 17):
            sample_right = _grid_sample(right, float(right_t))
            assert np.all(summed.contains(sample_left + sample_right))
            assert np.all(differenced.contains(sample_left - sample_right))
            assert np.all(multiplied.contains(sample_left * sample_right))
            assert np.all(divided.contains(sample_left / sample_right))
            assert np.all(reciprocal.contains(1.0 / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        sample_positive = _grid_sample(positive, float(left_t))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))

    # Independent random samples exercise distinct values in every array entry.
    rng = np.random.default_rng(20260827)
    for _ in range(128):
        sample_left = rng.uniform(left.lo, left.hi)
        sample_right = rng.uniform(right.lo, right.hi)
        sample_positive = rng.uniform(positive.lo, positive.hi)
        assert np.all(summed.contains(sample_left + sample_right))
        assert np.all(differenced.contains(sample_left - sample_right))
        assert np.all(multiplied.contains(sample_left * sample_right))
        assert np.all(divided.contains(sample_left / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))
        assert np.all(reciprocal.contains(1.0 / sample_right))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_elementwise_operations_enclose_grid_and_random_samples" -q
Method implementation
    def __truediv__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        return self * self.from_value(other).reciprocal()
View source ↗
__rtruediv__method
__rtruediv__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray

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

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Method implementation
    def __rtruediv__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        return self.from_value(other) * self.reciprocal()
View source ↗
__pow__method
__pow__(self, exponent: int) -> IntervalArray

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

Parameters

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

Returns: IntervalArray

Method implementation
    def __pow__(self, exponent: int) -> IntervalArray:
        return self.pow_int(exponent)
View source ↗
pow_intmethod
pow_int(self, exponent: int) -> IntervalArray

Outward-rounded elementwise integer powers via binary exponentiation.

Parameters

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

Returns: IntervalArray

Validation & failure cases
  • When not isinstance(exponent, int), raises TypeError('interval power exponent must be an integer').
Executed regression · elementwise operations enclose grid and random samples

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_elementwise_operations_enclose_grid_and_random_samples() -> None:
    """All scalar operations remain sound in the vectorized representation."""
    left = IntervalArray(
        [[-1.5, 0.25, 2.0], [-0.8, -3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, -0.4, 2.2]],
    )
    right = IntervalArray(
        [[0.2, 1.1, 0.5], [0.7, 0.25, 1.5]],
        [[1.4, 2.3, 1.8], [1.9, 0.75, 3.0]],
    )
    positive = IntervalArray(
        [[0.0, 0.25, 2.0], [0.8, 3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, 4.0, 2.2]],
    )

    summed = left + right
    differenced = left - right
    multiplied = left * right
    divided = left / right
    squared = left.pow_int(2)
    cubed = left.pow_int(3)
    absolute = left.abs()
    rooted = positive.sqrt()
    reciprocal = right.reciprocal()
    _assert_encloses_scalar(summed, lambda x, y: x + y, left, right)
    _assert_encloses_scalar(differenced, lambda x, y: x - y, left, right)
    _assert_encloses_scalar(multiplied, lambda x, y: x * y, left, right)
    _assert_encloses_scalar(divided, lambda x, y: x / y, left, right)
    for index in np.ndindex(left.shape):
        scalar = _scalar_at(left, index)
        scalar_positive = _scalar_at(positive, index)
        scalar_right = _scalar_at(right, index)
        assert squared.lo[index] <= scalar.pow_int(2).lo <= scalar.pow_int(2).hi <= squared.hi[index]
        assert cubed.lo[index] <= scalar.pow_int(3).lo <= scalar.pow_int(3).hi <= cubed.hi[index]
        assert absolute.lo[index] <= scalar.abs().lo <= scalar.abs().hi <= absolute.hi[index]
        assert rooted.lo[index] <= scalar_positive.sqrt().lo <= scalar_positive.sqrt().hi <= rooted.hi[index]
        assert (
            reciprocal.lo[index]
            <= scalar_right.reciprocal().lo
            <= scalar_right.reciprocal().hi
            <= reciprocal.hi[index]
        )

    # Dense deterministic interior grid.
    for left_t in np.linspace(0.0, 1.0, 17):
        sample_left = _grid_sample(left, float(left_t))
        for right_t in np.linspace(0.0, 1.0, 17):
            sample_right = _grid_sample(right, float(right_t))
            assert np.all(summed.contains(sample_left + sample_right))
            assert np.all(differenced.contains(sample_left - sample_right))
            assert np.all(multiplied.contains(sample_left * sample_right))
            assert np.all(divided.contains(sample_left / sample_right))
            assert np.all(reciprocal.contains(1.0 / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        sample_positive = _grid_sample(positive, float(left_t))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))

    # Independent random samples exercise distinct values in every array entry.
    rng = np.random.default_rng(20260827)
    for _ in range(128):
        sample_left = rng.uniform(left.lo, left.hi)
        sample_right = rng.uniform(right.lo, right.hi)
        sample_positive = rng.uniform(positive.lo, positive.hi)
        assert np.all(summed.contains(sample_left + sample_right))
        assert np.all(differenced.contains(sample_left - sample_right))
        assert np.all(multiplied.contains(sample_left * sample_right))
        assert np.all(divided.contains(sample_left / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))
        assert np.all(reciprocal.contains(1.0 / sample_right))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_elementwise_operations_enclose_grid_and_random_samples" -q
Method implementation
    def pow_int(self, exponent: int) -> IntervalArray:
        """Outward-rounded elementwise integer powers via binary exponentiation."""
        if not isinstance(exponent, int):
            raise TypeError("interval power exponent must be an integer")
        if exponent < 0:
            return self.pow_int(-exponent).reciprocal()
        result = IntervalArray.point(np.ones(self.shape, dtype=np.float64))
        base = self.abs() if exponent % 2 == 0 else self
        remaining = exponent
        while remaining > 0:
            if remaining & 1:
                result = result * base
            remaining >>= 1
            if remaining > 0:
                base = base * base
        return result
View source ↗
absmethod
abs(self) -> IntervalArray

Elementwise enclosure of absolute value.

Returns: IntervalArray

Executed regression · elementwise operations enclose grid and random samples

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_elementwise_operations_enclose_grid_and_random_samples() -> None:
    """All scalar operations remain sound in the vectorized representation."""
    left = IntervalArray(
        [[-1.5, 0.25, 2.0], [-0.8, -3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, -0.4, 2.2]],
    )
    right = IntervalArray(
        [[0.2, 1.1, 0.5], [0.7, 0.25, 1.5]],
        [[1.4, 2.3, 1.8], [1.9, 0.75, 3.0]],
    )
    positive = IntervalArray(
        [[0.0, 0.25, 2.0], [0.8, 3.0, 0.4]],
        [[0.5, 1.75, 3.5], [1.2, 4.0, 2.2]],
    )

    summed = left + right
    differenced = left - right
    multiplied = left * right
    divided = left / right
    squared = left.pow_int(2)
    cubed = left.pow_int(3)
    absolute = left.abs()
    rooted = positive.sqrt()
    reciprocal = right.reciprocal()
    _assert_encloses_scalar(summed, lambda x, y: x + y, left, right)
    _assert_encloses_scalar(differenced, lambda x, y: x - y, left, right)
    _assert_encloses_scalar(multiplied, lambda x, y: x * y, left, right)
    _assert_encloses_scalar(divided, lambda x, y: x / y, left, right)
    for index in np.ndindex(left.shape):
        scalar = _scalar_at(left, index)
        scalar_positive = _scalar_at(positive, index)
        scalar_right = _scalar_at(right, index)
        assert squared.lo[index] <= scalar.pow_int(2).lo <= scalar.pow_int(2).hi <= squared.hi[index]
        assert cubed.lo[index] <= scalar.pow_int(3).lo <= scalar.pow_int(3).hi <= cubed.hi[index]
        assert absolute.lo[index] <= scalar.abs().lo <= scalar.abs().hi <= absolute.hi[index]
        assert rooted.lo[index] <= scalar_positive.sqrt().lo <= scalar_positive.sqrt().hi <= rooted.hi[index]
        assert (
            reciprocal.lo[index]
            <= scalar_right.reciprocal().lo
            <= scalar_right.reciprocal().hi
            <= reciprocal.hi[index]
        )

    # Dense deterministic interior grid.
    for left_t in np.linspace(0.0, 1.0, 17):
        sample_left = _grid_sample(left, float(left_t))
        for right_t in np.linspace(0.0, 1.0, 17):
            sample_right = _grid_sample(right, float(right_t))
            assert np.all(summed.contains(sample_left + sample_right))
            assert np.all(differenced.contains(sample_left - sample_right))
            assert np.all(multiplied.contains(sample_left * sample_right))
            assert np.all(divided.contains(sample_left / sample_right))
            assert np.all(reciprocal.contains(1.0 / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        sample_positive = _grid_sample(positive, float(left_t))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))

    # Independent random samples exercise distinct values in every array entry.
    rng = np.random.default_rng(20260827)
    for _ in range(128):
        sample_left = rng.uniform(left.lo, left.hi)
        sample_right = rng.uniform(right.lo, right.hi)
        sample_positive = rng.uniform(positive.lo, positive.hi)
        assert np.all(summed.contains(sample_left + sample_right))
        assert np.all(differenced.contains(sample_left - sample_right))
        assert np.all(multiplied.contains(sample_left * sample_right))
        assert np.all(divided.contains(sample_left / sample_right))
        assert np.all(squared.contains(sample_left**2))
        assert np.all(cubed.contains(sample_left**3))
        assert np.all(absolute.contains(np.abs(sample_left)))
        assert np.all(rooted.contains(np.sqrt(sample_positive)))
        assert np.all(reciprocal.contains(1.0 / sample_right))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_elementwise_operations_enclose_grid_and_random_samples" -q
Method implementation
    def abs(self) -> IntervalArray:
        """Elementwise enclosure of absolute value."""
        nonnegative = self.lo >= 0.0
        nonpositive = self.hi <= 0.0
        straddles_zero = ~(nonnegative | nonpositive)
        lower = cast(
            FloatArray,
            np.where(nonnegative, self.lo, np.where(nonpositive, -self.hi, 0.0)),
        )
        upper_raw = cast(
            FloatArray,
            np.where(nonnegative, self.hi, np.where(nonpositive, -self.lo, 0.0)),
        )
        upper = cast(
            FloatArray,
            np.where(
                straddles_zero,
                _succ(cast(FloatArray, np.maximum(-self.lo, self.hi))),
                upper_raw,
            ),
        )
        return IntervalArray(lower, upper)
View source ↗
sqrtmethod
sqrt(self) -> IntervalArray

Elementwise square root; every entry must be non-negative.

Returns: IntervalArray

Validation & failure cases
  • When bool(np.any(self.lo < 0.0)), raises ValueError('sqrt requires non-negative intervals').
Executed regression · hull properties and domain checks

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_hull_properties_and_domain_checks() -> None:
    left = IntervalArray([-2.0, 1.0], [-1.0, 3.0])
    right = IntervalArray([-1.5, -4.0], [0.5, 2.0])
    combined = IntervalArray.hull(left, right, 0.0)
    assert np.all(combined.lo <= left.lo)
    assert np.all(left.hi <= combined.hi)
    assert np.all(combined.lo <= right.lo)
    assert np.all(right.hi <= combined.hi)
    assert np.all(combined.contains(0.0))
    assert np.all(combined.mid >= combined.lo)
    assert np.all(combined.mid <= combined.hi)
    assert np.all(combined.rad >= 0.0)
    assert np.all(combined.width >= 0.0)
    assert np.all(combined.mag >= combined.mig)
    with pytest.raises(ZeroDivisionError, match="zero outside"):
        IntervalArray([-1.0], [1.0]).reciprocal()
    with pytest.raises(ValueError, match="non-negative"):
        left.sqrt()
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_hull_properties_and_domain_checks" -q
Method implementation
    def sqrt(self) -> IntervalArray:
        """Elementwise square root; every entry must be non-negative."""
        if bool(np.any(self.lo < 0.0)):
            raise ValueError("sqrt requires non-negative intervals")
        return IntervalArray(_pred(np.sqrt(self.lo)), _succ(np.sqrt(self.hi)))
View source ↗
intersectmethod
intersect(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray

Elementwise intersection; raises when any entry is empty.

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Validation & failure cases
  • When bool(np.any(lo > hi)), raises ValueError('empty interval intersection').
Method implementation
    def intersect(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Elementwise intersection; raises when any entry is empty."""
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        lo = cast(FloatArray, np.maximum(left_lo, right_lo))
        hi = cast(FloatArray, np.minimum(left_hi, right_hi))
        if bool(np.any(lo > hi)):
            raise ValueError("empty interval intersection")
        return IntervalArray(lo, hi)
View source ↗
dotmethod
dot(self, other: IntervalArray | Interval | ArrayLike) -> Interval

Rigorous dot product of two one-dimensional interval arrays.

Parameters

NameType & defaultContract
otherpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: Interval

Validation & failure cases
  • When self.ndim != 1 or right.ndim != 1 or self.shape != right.shape, raises ValueError('dot requires one-dimensional operands of equal shape').
Executed regression · dense and sparse matvec and dot are sound

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_dense_and_sparse_matvec_and_dot_are_sound() -> None:
    """Products use outward accumulation and agree componentwise with Interval."""
    matrix = IntervalArray(
        [[0.5, -1.3, 0.2], [1.1, -0.7, 0.4]],
        [[1.2, -0.3, 0.9], [1.8, 0.2, 1.1]],
    )
    vector = IntervalArray([-0.8, 0.5, 1.2], [0.6, 1.5, 2.0])
    dense = matrix.matvec(vector)
    rows = np.asarray([0, 0, 0, 1, 1, 1])
    columns = np.asarray([0, 1, 2, 0, 1, 2])
    entries = IntervalArray(matrix.lo[rows, columns], matrix.hi[rows, columns])
    sparse = sparse_matvec(rows, columns, entries, vector, matrix.shape)
    dot = vector.dot(vector)

    for row in range(matrix.shape[0]):
        scalar_sum = Interval.point(0.0)
        for column in range(matrix.shape[1]):
            scalar_sum = scalar_sum + _scalar_at(matrix, (row, column)) * _scalar_at(
                vector, (column,)
            )
        assert dense.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= dense.hi[row]
        assert sparse.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= sparse.hi[row]
    scalar_dot = Interval.point(0.0)
    for value in range(vector.shape[0]):
        scalar_dot = scalar_dot + _scalar_at(vector, (value,)) * _scalar_at(vector, (value,))
    assert dot.lo <= scalar_dot.lo <= scalar_dot.hi <= dot.hi

    # Dense deterministic samples and independent random samples.
    rng = np.random.default_rng(20260827)
    samples = [
        (
            _grid_sample(matrix, float(t)),
            _grid_sample(vector, float(1.0 - t)),
        )
        for t in np.linspace(0.0, 1.0, 17)
    ]
    samples.extend(
        (rng.uniform(matrix.lo, matrix.hi), rng.uniform(vector.lo, vector.hi))
        for _ in range(128)
    )
    for matrix_sample, vector_sample in samples:
        expected = matrix_sample @ vector_sample
        assert np.all(dense.contains(expected))
        assert np.all(sparse.contains(expected))
        assert dot.contains(float(vector_sample @ vector_sample))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_dense_and_sparse_matvec_and_dot_are_sound" -q
Method implementation
    def dot(self, other: IntervalArray | Interval | ArrayLike) -> Interval:
        """Rigorous dot product of two one-dimensional interval arrays."""
        right = self.from_value(other)
        if self.ndim != 1 or right.ndim != 1 or self.shape != right.shape:
            raise ValueError("dot requires one-dimensional operands of equal shape")
        products = self * right
        lo = 0.0
        hi = 0.0
        for lower, upper in zip(products.lo, products.hi, strict=True):
            lo = float(np.nextafter(lo + float(lower), -np.inf))
            hi = float(np.nextafter(hi + float(upper), np.inf))
        return Interval(lo, hi)
View source ↗
matvecmethod
matvec(self, vector: IntervalArray | Interval | ArrayLike) -> IntervalArray

Rigorous dense matrix-vector product with outward accumulation.

Parameters

NameType & defaultContract
vectorpositional-or-keywordIntervalArray | Interval | ArrayLikeRequiredSee the operation contract and implementation below.

Returns: IntervalArray

Validation & failure cases
  • When self.ndim != 2 or values.ndim != 1 or self.shape[1] != values.shape[0], raises ValueError('matvec requires an (m, n) matrix and length-n vector').
Executed regression · dense and sparse matvec and dot are sound

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_dense_and_sparse_matvec_and_dot_are_sound() -> None:
    """Products use outward accumulation and agree componentwise with Interval."""
    matrix = IntervalArray(
        [[0.5, -1.3, 0.2], [1.1, -0.7, 0.4]],
        [[1.2, -0.3, 0.9], [1.8, 0.2, 1.1]],
    )
    vector = IntervalArray([-0.8, 0.5, 1.2], [0.6, 1.5, 2.0])
    dense = matrix.matvec(vector)
    rows = np.asarray([0, 0, 0, 1, 1, 1])
    columns = np.asarray([0, 1, 2, 0, 1, 2])
    entries = IntervalArray(matrix.lo[rows, columns], matrix.hi[rows, columns])
    sparse = sparse_matvec(rows, columns, entries, vector, matrix.shape)
    dot = vector.dot(vector)

    for row in range(matrix.shape[0]):
        scalar_sum = Interval.point(0.0)
        for column in range(matrix.shape[1]):
            scalar_sum = scalar_sum + _scalar_at(matrix, (row, column)) * _scalar_at(
                vector, (column,)
            )
        assert dense.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= dense.hi[row]
        assert sparse.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= sparse.hi[row]
    scalar_dot = Interval.point(0.0)
    for value in range(vector.shape[0]):
        scalar_dot = scalar_dot + _scalar_at(vector, (value,)) * _scalar_at(vector, (value,))
    assert dot.lo <= scalar_dot.lo <= scalar_dot.hi <= dot.hi

    # Dense deterministic samples and independent random samples.
    rng = np.random.default_rng(20260827)
    samples = [
        (
            _grid_sample(matrix, float(t)),
            _grid_sample(vector, float(1.0 - t)),
        )
        for t in np.linspace(0.0, 1.0, 17)
    ]
    samples.extend(
        (rng.uniform(matrix.lo, matrix.hi), rng.uniform(vector.lo, vector.hi))
        for _ in range(128)
    )
    for matrix_sample, vector_sample in samples:
        expected = matrix_sample @ vector_sample
        assert np.all(dense.contains(expected))
        assert np.all(sparse.contains(expected))
        assert dot.contains(float(vector_sample @ vector_sample))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_dense_and_sparse_matvec_and_dot_are_sound" -q
Method implementation
    def matvec(self, vector: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Rigorous dense matrix-vector product with outward accumulation."""
        values = self.from_value(vector)
        if self.ndim != 2 or values.ndim != 1 or self.shape[1] != values.shape[0]:
            raise ValueError("matvec requires an (m, n) matrix and length-n vector")
        products = self * values
        lower = np.zeros(self.shape[0], dtype=np.float64)
        upper = np.zeros(self.shape[0], dtype=np.float64)
        for column in range(self.shape[1]):
            lower = _pred(lower + products.lo[:, column])
            upper = _succ(upper + products.hi[:, column])
        return IntervalArray(lower, upper)
View source ↗
__repr__method
__repr__(self) -> str

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

Returns: str

Method implementation
    def __repr__(self) -> str:
        return f"IntervalArray(lo={self.lo!r}, hi={self.hi!r})"
View source ↗
Read the implementation
class IntervalArray:
    """A shape-preserving array of closed real intervals.

    The constructor accepts matching or broadcastable lower and upper endpoint
    arrays.  It does not round those endpoints; callers must provide values that
    already enclose the intended reals.  :meth:`point` is appropriate when a
    binary64 array is the literal input datum.
    """

    lo: FloatArray
    hi: FloatArray

    __array_priority__ = 1000

    def __init__(self, lo: ArrayLike, hi: ArrayLike) -> None:
        lo_raw = _as_float_array(lo)
        hi_raw = _as_float_array(hi)
        try:
            lo_arr, hi_arr = np.broadcast_arrays(lo_raw, hi_raw)
        except ValueError as exc:
            raise ValueError("interval endpoint shapes are not broadcastable") from exc
        lo_out = cast(FloatArray, np.array(lo_arr, dtype=np.float64, copy=True))
        hi_out = cast(FloatArray, np.array(hi_arr, dtype=np.float64, copy=True))
        if bool(np.any(np.isnan(lo_out))) or bool(np.any(np.isnan(hi_out))):
            raise ValueError("interval endpoints must not be NaN")
        if bool(np.any(lo_out > hi_out)):
            raise ValueError("interval lower endpoint exceeds upper endpoint")
        lo_out.setflags(write=False)
        hi_out.setflags(write=False)
        object.__setattr__(self, "lo", lo_out)
        object.__setattr__(self, "hi", hi_out)

    @classmethod
    def point(cls, value: ArrayLike) -> IntervalArray:
        """Exact point intervals for binary64 input data."""
        values = _as_float_array(value)
        return cls(values, values)

    @classmethod
    def from_value(cls, value: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Promote interval or scalar/array data to an interval array."""
        if isinstance(value, IntervalArray):
            return value
        if isinstance(value, Interval):
            return cls(np.asarray(value.lo), np.asarray(value.hi))
        return cls.point(value)

    @classmethod
    def from_intervals(cls, values: ArrayLike) -> IntervalArray:
        """Build a one-dimensional interval array from scalar :class:`Interval`s."""
        raw = np.asarray(values, dtype=object)
        if raw.ndim != 1:
            raise ValueError("from_intervals requires a one-dimensional sequence")
        if not all(isinstance(value, Interval) for value in raw):
            raise TypeError("from_intervals requires only Interval values")
        return cls(
            np.asarray([value.lo for value in raw], dtype=np.float64),
            np.asarray([value.hi for value in raw], dtype=np.float64),
        )

    @classmethod
    def hull(cls, *values: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Smallest elementwise interval array containing every supplied input."""
        if not values:
            raise ValueError("hull requires at least one value")
        intervals = [cls.from_value(value) for value in values]
        try:
            lows = np.broadcast_arrays(*(interval.lo for interval in intervals))
            highs = np.broadcast_arrays(*(interval.hi for interval in intervals))
        except ValueError as exc:
            raise ValueError("hull inputs are not broadcastable") from exc
        return cls(
            cast(FloatArray, np.min(np.stack(lows), axis=0)),
            cast(FloatArray, np.max(np.stack(highs), axis=0)),
        )

    @property
    def shape(self) -> tuple[int, ...]:
        """The common endpoint shape."""
        return self.lo.shape

    @property
    def ndim(self) -> int:
        """Number of array dimensions."""
        return self.lo.ndim

    @property
    def size(self) -> int:
        """Total number of scalar intervals."""
        return self.lo.size

    @property
    def mid(self) -> FloatArray:
        """A representable midpoint array contained in each interval."""
        midpoint = 0.5 * self.lo + 0.5 * self.hi
        midpoint = cast(
            FloatArray,
            np.where(np.isneginf(self.lo) & np.isposinf(self.hi), 0.0, midpoint),
        )
        midpoint = cast(FloatArray, np.maximum(self.lo, midpoint))
        return cast(FloatArray, np.minimum(self.hi, midpoint))

    @property
    def rad(self) -> FloatArray:
        """Outward-rounded radius array."""
        midpoint = self.mid
        return _succ(cast(FloatArray, np.maximum(midpoint - self.lo, self.hi - midpoint)))

    @property
    def width(self) -> FloatArray:
        """Outward-rounded widths."""
        return _succ(self.hi - self.lo)

    @property
    def mag(self) -> FloatArray:
        """Outward-rounded elementwise magnitude bounds."""
        return _succ(cast(FloatArray, np.maximum(np.abs(self.lo), np.abs(self.hi))))

    @property
    def mig(self) -> FloatArray:
        """Outward-rounded elementwise mignitudes."""
        straddles_zero = (self.lo <= 0.0) & (0.0 <= self.hi)
        nonzero = _pred(cast(FloatArray, np.minimum(np.abs(self.lo), np.abs(self.hi))))
        return cast(FloatArray, np.where(straddles_zero, 0.0, nonzero))

    def contains(self, value: ArrayLike) -> BoolArray:
        """Elementwise containment test, with NumPy broadcasting."""
        values = _as_float_array(value)
        try:
            lo, hi, points = np.broadcast_arrays(self.lo, self.hi, values)
        except ValueError as exc:
            raise ValueError("containment value is not broadcastable") from exc
        return (lo <= points) & (points <= hi)

    def contains_zero(self) -> BoolArray:
        """Elementwise test for whether zero belongs to each interval."""
        return (self.lo <= 0.0) & (0.0 <= self.hi)

    def _broadcast(
        self, other: IntervalArray | Interval | ArrayLike
    ) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray]:
        right = self.from_value(other)
        try:
            left_lo, left_hi, right_lo, right_hi = np.broadcast_arrays(
                self.lo, self.hi, right.lo, right.hi
            )
        except ValueError as exc:
            raise ValueError("interval operand shapes are not broadcastable") from exc
        return (
            cast(FloatArray, left_lo),
            cast(FloatArray, left_hi),
            cast(FloatArray, right_lo),
            cast(FloatArray, right_hi),
        )

    def __add__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        return IntervalArray(_pred(left_lo + right_lo), _succ(left_hi + right_hi))

    __radd__ = __add__

    def __neg__(self) -> IntervalArray:
        return IntervalArray(-self.hi, -self.lo)

    def __sub__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        return IntervalArray(_pred(left_lo - right_hi), _succ(left_hi - right_lo))

    def __rsub__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        return self.from_value(other).__sub__(self)

    def __mul__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        lo, hi = _mul_bounds(left_lo, left_hi, right_lo, right_hi)
        return IntervalArray(lo, hi)

    __rmul__ = __mul__

    def reciprocal(self) -> IntervalArray:
        """Elementwise reciprocal; every entry must exclude zero."""
        if bool(np.any(self.contains_zero())):
            raise ZeroDivisionError("interval reciprocal requires zero outside every interval")
        return IntervalArray(_pred(1.0 / self.hi), _succ(1.0 / self.lo))

    def __truediv__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        return self * self.from_value(other).reciprocal()

    def __rtruediv__(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        return self.from_value(other) * self.reciprocal()

    def __pow__(self, exponent: int) -> IntervalArray:
        return self.pow_int(exponent)

    def pow_int(self, exponent: int) -> IntervalArray:
        """Outward-rounded elementwise integer powers via binary exponentiation."""
        if not isinstance(exponent, int):
            raise TypeError("interval power exponent must be an integer")
        if exponent < 0:
            return self.pow_int(-exponent).reciprocal()
        result = IntervalArray.point(np.ones(self.shape, dtype=np.float64))
        base = self.abs() if exponent % 2 == 0 else self
        remaining = exponent
        while remaining > 0:
            if remaining & 1:
                result = result * base
            remaining >>= 1
            if remaining > 0:
                base = base * base
        return result

    def abs(self) -> IntervalArray:
        """Elementwise enclosure of absolute value."""
        nonnegative = self.lo >= 0.0
        nonpositive = self.hi <= 0.0
        straddles_zero = ~(nonnegative | nonpositive)
        lower = cast(
            FloatArray,
            np.where(nonnegative, self.lo, np.where(nonpositive, -self.hi, 0.0)),
        )
        upper_raw = cast(
            FloatArray,
            np.where(nonnegative, self.hi, np.where(nonpositive, -self.lo, 0.0)),
        )
        upper = cast(
            FloatArray,
            np.where(
                straddles_zero,
                _succ(cast(FloatArray, np.maximum(-self.lo, self.hi))),
                upper_raw,
            ),
        )
        return IntervalArray(lower, upper)

    __abs__ = abs

    def sqrt(self) -> IntervalArray:
        """Elementwise square root; every entry must be non-negative."""
        if bool(np.any(self.lo < 0.0)):
            raise ValueError("sqrt requires non-negative intervals")
        return IntervalArray(_pred(np.sqrt(self.lo)), _succ(np.sqrt(self.hi)))

    def intersect(self, other: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Elementwise intersection; raises when any entry is empty."""
        left_lo, left_hi, right_lo, right_hi = self._broadcast(other)
        lo = cast(FloatArray, np.maximum(left_lo, right_lo))
        hi = cast(FloatArray, np.minimum(left_hi, right_hi))
        if bool(np.any(lo > hi)):
            raise ValueError("empty interval intersection")
        return IntervalArray(lo, hi)

    def dot(self, other: IntervalArray | Interval | ArrayLike) -> Interval:
        """Rigorous dot product of two one-dimensional interval arrays."""
        right = self.from_value(other)
        if self.ndim != 1 or right.ndim != 1 or self.shape != right.shape:
            raise ValueError("dot requires one-dimensional operands of equal shape")
        products = self * right
        lo = 0.0
        hi = 0.0
        for lower, upper in zip(products.lo, products.hi, strict=True):
            lo = float(np.nextafter(lo + float(lower), -np.inf))
            hi = float(np.nextafter(hi + float(upper), np.inf))
        return Interval(lo, hi)

    def matvec(self, vector: IntervalArray | Interval | ArrayLike) -> IntervalArray:
        """Rigorous dense matrix-vector product with outward accumulation."""
        values = self.from_value(vector)
        if self.ndim != 2 or values.ndim != 1 or self.shape[1] != values.shape[0]:
            raise ValueError("matvec requires an (m, n) matrix and length-n vector")
        products = self * values
        lower = np.zeros(self.shape[0], dtype=np.float64)
        upper = np.zeros(self.shape[0], dtype=np.float64)
        for column in range(self.shape[1]):
            lower = _pred(lower + products.lo[:, column])
            upper = _succ(upper + products.hi[:, column])
        return IntervalArray(lower, upper)

    def __repr__(self) -> str:
        return f"IntervalArray(lo={self.lo!r}, hi={self.hi!r})"
Other public import paths
  • omnibias.core.verified.IntervalArray
  • omnibias.core.verified.interval_array.IntervalArray
CONSTANT

IntervalArrayLike​

omnibias.core.verified.IntervalArrayLikeSource ↗
IntervalArrayLike: TypeAlias = IntervalArray | Interval | ArrayLike

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
IntervalArrayLike: TypeAlias = IntervalArray | Interval | ArrayLike
Other public import paths
  • omnibias.core.verified.IntervalArrayLike
  • omnibias.core.verified.interval_array.IntervalArrayLike
FUNCTION

dot​

omnibias.core.verified.dotSource ↗
dot(left: IntervalArrayLike, right: IntervalArrayLike) -> Interval

Rigorous one-dimensional interval dot product.

Parameters

NameType & defaultContract
leftpositional-or-keywordIntervalArrayLikeRequiredSee the operation contract and implementation below.
rightpositional-or-keywordIntervalArrayLikeRequiredSee the operation contract and implementation below.
ReturnsInterval
Read the implementation
def dot(left: IntervalArrayLike, right: IntervalArrayLike) -> Interval:
    """Rigorous one-dimensional interval dot product."""
    return IntervalArray.from_value(left).dot(right)
Other public import paths
  • omnibias.core.verified.dot
  • omnibias.core.verified.interval_array.dot
FUNCTION

sparse_matvec​

omnibias.core.verified.sparse_matvecSource ↗
sparse_matvec(rows: ArrayLike, columns: ArrayLike, data: IntervalArrayLike, vector: IntervalArrayLike, shape: tuple[int, int]) -> IntervalArray

Rigorous COO sparse matrix-vector product.

rows[k], columns[k], and data[k] specify one matrix entry. Duplicate entries are accumulated separately, as required for COO input.

Parameters

NameType & defaultContract
rowspositional-or-keywordArrayLikeRequiredSee the operation contract and implementation below.
columnspositional-or-keywordArrayLikeRequiredSee the operation contract and implementation below.
datapositional-or-keywordIntervalArrayLikeRequiredSee the operation contract and implementation below.
vectorpositional-or-keywordIntervalArrayLikeRequiredSee the operation contract and implementation below.
shapepositional-or-keywordtuple[int, int]RequiredSee the operation contract and implementation below.
ReturnsIntervalArray
Explicit validation & failure cases
  • When n_rows < 0 or n_columns < 0, raises ValueError('sparse matrix dimensions must be non-negative').
  • When raw_rows.ndim != 1 or raw_columns.ndim != 1, raises ValueError('COO row and column indices must be one-dimensional').
  • When raw_rows.shape != raw_columns.shape, raises ValueError('COO row and column indices must have equal length').
  • When not np.issubdtype(raw_rows.dtype, np.integer) or not np.issubdtype(raw_columns.dtype, np.integer), raises TypeError('COO row and column indices must be integers').
  • When bool(np.any(row_indices < 0)) or bool(np.any(row_indices >= n_rows)), raises ValueError('COO row index outside sparse matrix shape').
  • When bool(np.any(column_indices < 0)) or bool(np.any(column_indices >= n_columns)), raises ValueError('COO column index outside sparse matrix shape').
  • When entries.ndim != 1 or entries.shape[0] != row_indices.shape[0], raises ValueError('COO data must be one-dimensional with one entry per index').
  • When values.ndim != 1 or values.shape[0] != n_columns, raises ValueError('sparse matvec vector length does not match shape').

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

Executed regression · dense and sparse matvec and dot are sound

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_dense_and_sparse_matvec_and_dot_are_sound() -> None:
    """Products use outward accumulation and agree componentwise with Interval."""
    matrix = IntervalArray(
        [[0.5, -1.3, 0.2], [1.1, -0.7, 0.4]],
        [[1.2, -0.3, 0.9], [1.8, 0.2, 1.1]],
    )
    vector = IntervalArray([-0.8, 0.5, 1.2], [0.6, 1.5, 2.0])
    dense = matrix.matvec(vector)
    rows = np.asarray([0, 0, 0, 1, 1, 1])
    columns = np.asarray([0, 1, 2, 0, 1, 2])
    entries = IntervalArray(matrix.lo[rows, columns], matrix.hi[rows, columns])
    sparse = sparse_matvec(rows, columns, entries, vector, matrix.shape)
    dot = vector.dot(vector)

    for row in range(matrix.shape[0]):
        scalar_sum = Interval.point(0.0)
        for column in range(matrix.shape[1]):
            scalar_sum = scalar_sum + _scalar_at(matrix, (row, column)) * _scalar_at(
                vector, (column,)
            )
        assert dense.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= dense.hi[row]
        assert sparse.lo[row] <= scalar_sum.lo <= scalar_sum.hi <= sparse.hi[row]
    scalar_dot = Interval.point(0.0)
    for value in range(vector.shape[0]):
        scalar_dot = scalar_dot + _scalar_at(vector, (value,)) * _scalar_at(vector, (value,))
    assert dot.lo <= scalar_dot.lo <= scalar_dot.hi <= dot.hi

    # Dense deterministic samples and independent random samples.
    rng = np.random.default_rng(20260827)
    samples = [
        (
            _grid_sample(matrix, float(t)),
            _grid_sample(vector, float(1.0 - t)),
        )
        for t in np.linspace(0.0, 1.0, 17)
    ]
    samples.extend(
        (rng.uniform(matrix.lo, matrix.hi), rng.uniform(vector.lo, vector.hi))
        for _ in range(128)
    )
    for matrix_sample, vector_sample in samples:
        expected = matrix_sample @ vector_sample
        assert np.all(dense.contains(expected))
        assert np.all(sparse.contains(expected))
        assert dot.contains(float(vector_sample @ vector_sample))
python -m pytest "packages/omnibias-core/tests/verified/test_interval_array.py::test_dense_and_sparse_matvec_and_dot_are_sound" -q
Read the implementation
def sparse_matvec(
    rows: ArrayLike,
    columns: ArrayLike,
    data: IntervalArrayLike,
    vector: IntervalArrayLike,
    shape: tuple[int, int],
) -> IntervalArray:
    """Rigorous COO sparse matrix-vector product.

    ``rows[k]``, ``columns[k]``, and ``data[k]`` specify one matrix entry.
    Duplicate entries are accumulated separately, as required for COO input.
    """
    n_rows, n_columns = shape
    if n_rows < 0 or n_columns < 0:
        raise ValueError("sparse matrix dimensions must be non-negative")
    raw_rows = np.asarray(rows)
    raw_columns = np.asarray(columns)
    if raw_rows.ndim != 1 or raw_columns.ndim != 1:
        raise ValueError("COO row and column indices must be one-dimensional")
    if raw_rows.shape != raw_columns.shape:
        raise ValueError("COO row and column indices must have equal length")
    if not np.issubdtype(raw_rows.dtype, np.integer) or not np.issubdtype(
        raw_columns.dtype, np.integer
    ):
        raise TypeError("COO row and column indices must be integers")
    row_indices = np.asarray(raw_rows, dtype=np.intp)
    column_indices = np.asarray(raw_columns, dtype=np.intp)
    if bool(np.any(row_indices < 0)) or bool(np.any(row_indices >= n_rows)):
        raise ValueError("COO row index outside sparse matrix shape")
    if bool(np.any(column_indices < 0)) or bool(np.any(column_indices >= n_columns)):
        raise ValueError("COO column index outside sparse matrix shape")

    entries = IntervalArray.from_value(data)
    values = IntervalArray.from_value(vector)
    if entries.ndim != 1 or entries.shape[0] != row_indices.shape[0]:
        raise ValueError("COO data must be one-dimensional with one entry per index")
    if values.ndim != 1 or values.shape[0] != n_columns:
        raise ValueError("sparse matvec vector length does not match shape")

    lower = np.zeros(n_rows, dtype=np.float64)
    upper = np.zeros(n_rows, dtype=np.float64)
    for row, column, entry_lo, entry_hi in zip(
        row_indices, column_indices, entries.lo, entries.hi, strict=True
    ):
        product_lo, product_hi = _mul_bounds(
            np.asarray(entry_lo, dtype=np.float64),
            np.asarray(entry_hi, dtype=np.float64),
            np.asarray(values.lo[column], dtype=np.float64),
            np.asarray(values.hi[column], dtype=np.float64),
        )
        row_index = int(row)
        lower[row_index] = np.nextafter(lower[row_index] + product_lo.item(), -np.inf)
        upper[row_index] = np.nextafter(upper[row_index] + product_hi.item(), np.inf)
    return IntervalArray(lower, upper)
Other public import paths
  • omnibias.core.verified.sparse_matvec
  • omnibias.core.verified.interval_array.sparse_matvec