Skip to main content

omnibias.core.verified.taylor_model_mv

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

Multivariate Taylor models: rigorous enclosures over a box in R^n.

This is the dim-variable generalisation of omnibias.core.verified.taylor_model. A total-degree-order Taylor model on the box [c_i - r_i, c_i + r_i] is a pair

f(x) \in \sum_{|\alpha| \le N} a_\alpha\,(x - c)^\alpha + R \qquad \forall x \in \prod_i [c_i - r_i, c_i + r_i],

where the coefficients a_\alpha are Interval\s indexed by the canonical multi-index ordering of omnibias.core.multi_index, and the Interval remainder R rigorously absorbs every term the polynomial omits (both the truncation tail of a product and any pre-existing remainders).

Keeping the polynomial *shape* (rather than collapsing to a bare box) is what defeats the wrapping/dependency blow-up of naive interval evaluation, so the bound over the box stays tight even after several multiplications. This is the substrate the 2-D model-equation certificates (e.g. the Riesz/Leray operators in omnibias.core.verified.riesz) build on.

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

TaylorModelMV​

omnibias.core.verified.TaylorModelMVSource ↗
class TaylorModelMV

Total-degree-order multivariate Taylor model on a box.

Parameters

NameType & defaultContract
centerpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
radiuspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.
coeffspositional-or-keywordSequence[Interval]RequiredSee the operation contract and implementation below.
remainderpositional-or-keywordIntervalRequiredSee the operation contract and implementation below.
Executed regression · coefficient count must match

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_coefficient_count_must_match() -> None:
    with pytest.raises(ValueError):
        TaylorModelMV((0.0, 0.0), (1.0, 1.0), 2, [Interval.point(0.0)], Interval.point(0.0))
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_coefficient_count_must_match" -q
Regression example · coefficient layout matches multi index

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_coefficient_layout_matches_multi_index() -> None:
    order = 5
    tm = TaylorModelMV.constant(0.0, (0.0, 0.0), (1.0, 1.0), order)
    assert len(tm.coeffs) == num_multi_indices(2, order)
python -m pytest packages/omnibias-core/tests/verified/test_taylor_model_mv.py -k test_coefficient_layout_matches_multi_index -q

Fields & methods

__init__method
__init__(self, center: Sequence[float], radius: Sequence[float], order: int, coeffs: Sequence[Interval], remainder: Interval) -> None

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

Parameters

NameType & defaultContract
centerpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
radiuspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.
coeffspositional-or-keywordSequence[Interval]RequiredSee the operation contract and implementation below.
remainderpositional-or-keywordIntervalRequiredSee the operation contract and implementation below.

Returns: None

Validation & failure cases
  • When dim < 1, raises ValueError('a multivariate Taylor model needs dim >= 1').
  • When len(radius) != dim, raises ValueError('center and radius must have the same length').
  • When order < 0, raises ValueError('order must be >= 0').
  • When any((r < 0.0 for r in radius)), raises ValueError('box radii must be non-negative').
  • When len(coeffs) != expected, raises ValueError(f'expected {expected} coefficients for dim={dim}, order={order}, got {len(coeffs)}').
Executed regression · coefficient count must match

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_coefficient_count_must_match() -> None:
    with pytest.raises(ValueError):
        TaylorModelMV((0.0, 0.0), (1.0, 1.0), 2, [Interval.point(0.0)], Interval.point(0.0))
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_coefficient_count_must_match" -q
Method implementation
    def __init__(
        self,
        center: Sequence[float],
        radius: Sequence[float],
        order: int,
        coeffs: Sequence[Interval],
        remainder: Interval,
    ) -> None:
        dim = len(center)
        if dim < 1:
            raise ValueError("a multivariate Taylor model needs dim >= 1")
        if len(radius) != dim:
            raise ValueError("center and radius must have the same length")
        if order < 0:
            raise ValueError("order must be >= 0")
        if any(r < 0.0 for r in radius):
            raise ValueError("box radii must be non-negative")
        expected = num_multi_indices(dim, order)
        if len(coeffs) != expected:
            raise ValueError(
                f"expected {expected} coefficients for dim={dim}, order={order}, "
                f"got {len(coeffs)}"
            )
        self.center: tuple[float, ...] = tuple(float(c) for c in center)
        self.radius: tuple[float, ...] = tuple(float(r) for r in radius)
        self.dim = dim
        self.order = order
        self.coeffs: list[Interval] = list(coeffs)
        self.remainder = remainder
View source ↗
constantmethod
constant(cls, value: IntervalLike, center: Sequence[float], radius: Sequence[float], order: int) -> TaylorModelMV

The model of the constant function f(x) = value.

Parameters

NameType & defaultContract
valuepositional-or-keywordIntervalLikeRequiredSee the operation contract and implementation below.
centerpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
radiuspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: TaylorModelMV

Executed regression · coefficient layout matches multi index

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_coefficient_layout_matches_multi_index() -> None:
    order = 5
    tm = TaylorModelMV.constant(0.0, (0.0, 0.0), (1.0, 1.0), order)
    assert len(tm.coeffs) == num_multi_indices(2, order)
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_coefficient_layout_matches_multi_index" -q
Method implementation
    def constant(
        cls,
        value: IntervalLike,
        center: Sequence[float],
        radius: Sequence[float],
        order: int,
    ) -> TaylorModelMV:
        """The model of the constant function ``f(x) = value``."""
        n = num_multi_indices(len(center), order)
        coeffs = [Interval.point(0.0) for _ in range(n)]
        coeffs[0] = Interval.from_value(value)
        return cls(center, radius, order, coeffs, Interval.point(0.0))
View source ↗
coordinatemethod
coordinate(cls, axis: int, center: Sequence[float], radius: Sequence[float], order: int) -> TaylorModelMV

The model of the coordinate map f(x) = x_axis = c_axis + X_axis.

Parameters

NameType & defaultContract
axispositional-or-keywordintRequiredSee the operation contract and implementation below.
centerpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
radiuspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: TaylorModelMV

Validation & failure cases
  • When not 0 <= axis < dim, raises ValueError(f'axis {axis} out of range for dim {dim}').
  • When order < 1, raises ValueError('coordinate models need order >= 1').
Executed regression · coordinate bound is box axis

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_coordinate_bound_is_box_axis() -> None:
    tm = TaylorModelMV.coordinate(1, center=(0.5, 0.25), radius=(0.1, 0.25), order=4)
    b = tm.bound()
    assert b.lo <= 0.0  # 0.25 - 0.25
    assert b.hi >= 0.5  # 0.25 + 0.25
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_coordinate_bound_is_box_axis" -q
Method implementation
    def coordinate(
        cls,
        axis: int,
        center: Sequence[float],
        radius: Sequence[float],
        order: int,
    ) -> TaylorModelMV:
        """The model of the coordinate map ``f(x) = x_axis = c_axis + X_axis``."""
        dim = len(center)
        if not 0 <= axis < dim:
            raise ValueError(f"axis {axis} out of range for dim {dim}")
        if order < 1:
            raise ValueError("coordinate models need order >= 1")
        n = num_multi_indices(dim, order)
        coeffs = [Interval.point(0.0) for _ in range(n)]
        coeffs[0] = Interval.point(float(center[axis]))
        unit = tuple(1 if i == axis else 0 for i in range(dim))
        coeffs[index_position(dim, order)[unit]] = Interval.point(1.0)
        return cls(center, radius, order, coeffs, Interval.point(0.0))
View source ↗
boundmethod
bound(self) -> Interval

Guaranteed enclosure of f over the whole box.

Returns: Interval

Executed regression · constant model 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_model_is_tight() -> None:
    tm = TaylorModelMV.constant(3.5, center=(1.0, -2.0), radius=(2.0, 0.5), order=3)
    b = tm.bound()
    assert b.lo <= 3.5 <= b.hi
    assert b.width < 1e-12
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_constant_model_is_tight" -q
Method implementation
    def bound(self) -> Interval:
        """Guaranteed enclosure of ``f`` over the whole box."""
        return self._poly_bound() + self.remainder
View source ↗
evalmethod
eval(self, delta: Sequence[IntervalLike]) -> Interval

Enclosure of f(center + delta) for delta in the relative box.

delta is given relative to center (a point or sub-interval per axis); each must lie within [-r_i, r_i] for the enclosure to be valid. Passing the full relative box reproduces bound.

Parameters

NameType & defaultContract
deltapositional-or-keywordSequence[IntervalLike]RequiredSee the operation contract and implementation below.

Returns: Interval

Validation & failure cases
  • When len(delta) != self.dim, raises ValueError('delta must have one entry per dimension').
Executed regression · scalar and reverse ops

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_scalar_and_reverse_ops() -> None:
    center, radius = (0.0, 0.0), (0.5, 0.5)
    order = 3
    x = TaylorModelMV.coordinate(0, center, radius, order)
    g = 2.0 * x + 1.0
    h = 1.0 - x  # exercises __rsub__
    for xi, _yi in _grid(center, radius):
        assert g.eval((xi, 0.0)).lo <= 2.0 * xi + 1.0 <= g.eval((xi, 0.0)).hi
        assert h.eval((xi, 0.0)).lo <= 1.0 - xi <= h.eval((xi, 0.0)).hi
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_scalar_and_reverse_ops" -q
Method implementation
    def eval(self, delta: Sequence[IntervalLike]) -> Interval:
        r"""Enclosure of ``f(center + delta)`` for ``delta`` in the relative box.

        ``delta`` is given relative to ``center`` (a point or sub-interval per
        axis); each must lie within ``[-r_i, r_i]`` for the enclosure to be
        valid.  Passing the full relative box reproduces :meth:`bound`.
        """
        if len(delta) != self.dim:
            raise ValueError("delta must have one entry per dimension")
        dvals = [Interval.from_value(d) for d in delta]
        indices = multi_indices(self.dim, self.order)
        acc = Interval.point(0.0)
        for idx, coeff in zip(indices, self.coeffs, strict=True):
            if coeff.lo == 0.0 and coeff.hi == 0.0:
                continue
            mono = Interval.point(1.0)
            for axis, power in enumerate(idx):
                if power:
                    mono = mono * dvals[axis].pow_int(power)
            acc = acc + coeff * mono
        return acc + self.remainder
View source ↗
__add__method
__add__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV

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

Parameters

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

Returns: TaylorModelMV

Executed regression · scalar and reverse ops

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_scalar_and_reverse_ops() -> None:
    center, radius = (0.0, 0.0), (0.5, 0.5)
    order = 3
    x = TaylorModelMV.coordinate(0, center, radius, order)
    g = 2.0 * x + 1.0
    h = 1.0 - x  # exercises __rsub__
    for xi, _yi in _grid(center, radius):
        assert g.eval((xi, 0.0)).lo <= 2.0 * xi + 1.0 <= g.eval((xi, 0.0)).hi
        assert h.eval((xi, 0.0)).lo <= 1.0 - xi <= h.eval((xi, 0.0)).hi
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_scalar_and_reverse_ops" -q
Method implementation
    def __add__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV:
        if isinstance(other, TaylorModelMV):
            self._check(other)
            coeffs = [a + b for a, b in zip(self.coeffs, other.coeffs, strict=True)]
            return TaylorModelMV(
                self.center, self.radius, self.order, coeffs,
                self.remainder + other.remainder,
            )
        coeffs = list(self.coeffs)
        coeffs[0] = coeffs[0] + Interval.from_value(other)
        return TaylorModelMV(self.center, self.radius, self.order, coeffs, self.remainder)
View source ↗
__neg__method
__neg__(self) -> TaylorModelMV

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

Returns: TaylorModelMV

Executed regression · scalar and reverse ops

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_scalar_and_reverse_ops() -> None:
    center, radius = (0.0, 0.0), (0.5, 0.5)
    order = 3
    x = TaylorModelMV.coordinate(0, center, radius, order)
    g = 2.0 * x + 1.0
    h = 1.0 - x  # exercises __rsub__
    for xi, _yi in _grid(center, radius):
        assert g.eval((xi, 0.0)).lo <= 2.0 * xi + 1.0 <= g.eval((xi, 0.0)).hi
        assert h.eval((xi, 0.0)).lo <= 1.0 - xi <= h.eval((xi, 0.0)).hi
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_scalar_and_reverse_ops" -q
Method implementation
    def __neg__(self) -> TaylorModelMV:
        return TaylorModelMV(
            self.center, self.radius, self.order,
            [-c for c in self.coeffs], -self.remainder,
        )
View source ↗
__sub__method
__sub__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV

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

Parameters

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

Returns: TaylorModelMV

Executed regression · polynomial product encloses pointwise 2d

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_polynomial_product_encloses_pointwise_2d() -> None:
    center, radius = (0.3, -0.2), (0.4, 0.3)
    order = 6
    x = TaylorModelMV.coordinate(0, center, radius, order)
    y = TaylorModelMV.coordinate(1, center, radius, order)
    # f(x, y) = (x^2 + 1) * (y - 2) + x*y
    f = (x.pow_int(2) + 1.0) * (y - 2.0) + x * y
    b = f.bound()
    for xi, yi in _grid(center, radius):
        val = (xi * xi + 1.0) * (yi - 2.0) + xi * yi
        assert b.lo <= val <= b.hi
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_polynomial_product_encloses_pointwise_2d" -q
Method implementation
    def __sub__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV:
        if isinstance(other, TaylorModelMV):
            return self.__add__(-other)
        return self.__add__(-Interval.from_value(other))
View source ↗
__rsub__method
__rsub__(self, other: IntervalLike) -> TaylorModelMV

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

Parameters

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

Returns: TaylorModelMV

Executed regression · scalar and reverse ops

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_scalar_and_reverse_ops() -> None:
    center, radius = (0.0, 0.0), (0.5, 0.5)
    order = 3
    x = TaylorModelMV.coordinate(0, center, radius, order)
    g = 2.0 * x + 1.0
    h = 1.0 - x  # exercises __rsub__
    for xi, _yi in _grid(center, radius):
        assert g.eval((xi, 0.0)).lo <= 2.0 * xi + 1.0 <= g.eval((xi, 0.0)).hi
        assert h.eval((xi, 0.0)).lo <= 1.0 - xi <= h.eval((xi, 0.0)).hi
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_scalar_and_reverse_ops" -q
Method implementation
    def __rsub__(self, other: IntervalLike) -> TaylorModelMV:
        return (-self).__add__(Interval.from_value(other))
View source ↗
__mul__method
__mul__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV

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

Parameters

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

Returns: TaylorModelMV

Executed regression · scalar and reverse ops

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_scalar_and_reverse_ops() -> None:
    center, radius = (0.0, 0.0), (0.5, 0.5)
    order = 3
    x = TaylorModelMV.coordinate(0, center, radius, order)
    g = 2.0 * x + 1.0
    h = 1.0 - x  # exercises __rsub__
    for xi, _yi in _grid(center, radius):
        assert g.eval((xi, 0.0)).lo <= 2.0 * xi + 1.0 <= g.eval((xi, 0.0)).hi
        assert h.eval((xi, 0.0)).lo <= 1.0 - xi <= h.eval((xi, 0.0)).hi
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_scalar_and_reverse_ops" -q
Method implementation
    def __mul__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV:
        if not isinstance(other, TaylorModelMV):
            scal = Interval.from_value(other)
            return TaylorModelMV(
                self.center, self.radius, self.order,
                [c * scal for c in self.coeffs], self.remainder * scal,
            )
        self._check(other)
        indices = multi_indices(self.dim, self.order)
        pos = index_position(self.dim, self.order)
        n = len(self.coeffs)
        low = [Interval.point(0.0) for _ in range(n)]
        high = Interval.point(0.0)
        for ia in range(n):
            a = self.coeffs[ia]
            if a.lo == 0.0 and a.hi == 0.0:
                continue
            alpha = indices[ia]
            for ib in range(n):
                b = other.coeffs[ib]
                if b.lo == 0.0 and b.hi == 0.0:
                    continue
                gamma = tuple(alpha[k] + indices[ib][k] for k in range(self.dim))
                prod = a * b
                if sum(gamma) <= self.order:
                    low[pos[gamma]] = low[pos[gamma]] + prod
                else:
                    high = high + prod * _box_monomial(gamma, self.radius)
        # f*g = P*Q + P*Rg + Q*Rf + Rf*Rg, with the truncated P*Q tail in `high`.
        # Provably-zero remainder terms are skipped: this keeps an exact-polynomial
        # product exactly remainder-free (no spurious subnormal inflation) and is
        # cheaper, while staying rigorous (a [0,0] factor contributes nothing).
        remainder = high
        self_rzero = self.remainder.lo == 0.0 and self.remainder.hi == 0.0
        other_rzero = other.remainder.lo == 0.0 and other.remainder.hi == 0.0
        if not other_rzero:
            remainder = remainder + self._poly_bound() * other.remainder
        if not self_rzero:
            remainder = remainder + other._poly_bound() * self.remainder
        if not self_rzero and not other_rzero:
            remainder = remainder + self.remainder * other.remainder
        return TaylorModelMV(self.center, self.radius, self.order, low, remainder)
View source ↗
antiderivativemethod
antiderivative(self, axis: int) -> TaylorModelMV

Rigorous antiderivative along axis: F with d F / d x_axis = f.

Integration is the natural *sound* operation on a Taylor model. The polynomial part integrates term-by-term in the relative variable along axis (raising the total degree by one, so the result has order order + 1), with the integration constant fixed by F = 0 on the slice x_axis = center_axis. The remainder integrates rigorously to R \cdot [-r_axis, r_axis] (the mean-value enclosure of \int_0^{X_axis} e\,dt).

Parameters

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

Returns: TaylorModelMV

Validation & failure cases
  • When not 0 <= axis < self.dim, raises ValueError(f'axis {axis} out of range for dim {self.dim}').
Executed regression · mv antiderivative axis validation

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_mv_antiderivative_axis_validation() -> None:
    f = TaylorModelMV.constant(1.0, [0.0, 0.0], [0.5, 0.5], 1)
    with pytest.raises(ValueError):
        f.antiderivative(2)
    with pytest.raises(ValueError):
        f.antiderivative(-1)
python -m pytest "packages/omnibias-core/tests/test_verified_tm_integral.py::test_mv_antiderivative_axis_validation" -q
Method implementation
    def antiderivative(self, axis: int) -> TaylorModelMV:
        r"""Rigorous antiderivative along ``axis``: ``F`` with ``d F / d x_axis = f``.

        Integration is the natural *sound* operation on a Taylor model.  The
        polynomial part integrates term-by-term in the relative variable along
        ``axis`` (raising the total degree by one, so the result has order
        ``order + 1``), with the integration constant fixed by ``F = 0`` on the
        slice ``x_axis = center_axis``.  The remainder integrates rigorously to
        ``R \cdot [-r_axis, r_axis]`` (the mean-value enclosure of
        ``\int_0^{X_axis} e\,dt``).
        """
        if not 0 <= axis < self.dim:
            raise ValueError(f"axis {axis} out of range for dim {self.dim}")
        new_order = self.order + 1
        n_new = num_multi_indices(self.dim, new_order)
        pos_new = index_position(self.dim, new_order)
        old_indices = multi_indices(self.dim, self.order)
        new_coeffs = [Interval.point(0.0) for _ in range(n_new)]
        for c, alpha in zip(self.coeffs, old_indices, strict=True):
            if c.lo == 0.0 and c.hi == 0.0:
                continue
            beta = tuple(a + (1 if i == axis else 0) for i, a in enumerate(alpha))
            scale = Interval.from_rational(Fraction(1, alpha[axis] + 1))
            j = pos_new[beta]
            new_coeffs[j] = new_coeffs[j] + c * scale
        r_axis = self.radius[axis]
        rem = self.remainder * _rel_box([r_axis])[0]
        return TaylorModelMV(self.center, self.radius, new_order, new_coeffs, rem)
View source ↗
definite_integralmethod
definite_integral(self) -> Interval

Certified \int_{box} f(x)\,dx over the whole (symmetric) cell.

The multivariate generalisation of omnibias.core.verified.taylor_model.TaylorModel.definite_integral. On the symmetric box \prod_i [c_i - r_i, c_i + r_i] a monomial X^\alpha integrates to \prod_i \int_{-r_i}^{r_i} X_i^{\alpha_i} dX_i, which is 0 whenever any \alpha_i is odd and \prod_i 2\,r_i^{\alpha_i+1}/(\alpha_i+1) otherwise. The remainder contributes R \cdot \mathrm{vol} with \mathrm{vol} = \prod_i 2 r_i, since \int_{box} e(x)\,dx = \mathrm{vol}\cdot\bar e for a mean value \bar e \in R. Everything is outward-rounded, so the returned Interval provably contains the true integral over the box.

Returns: Interval

Executed regression · mv definite integral sound vs grid and random

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_mv_definite_integral_sound_vs_grid_and_random() -> None:
    """Mandatory soundness check (verified-enclosures rule): the certified
    definite integral contains the true value, cross-checked against a dense
    deterministic grid AND a random sample, with a *genuine* remainder.

    ``g(x, y) = (x + y)^4`` is enclosed by an order-2 Taylor model, so every
    degree-``> 2`` term is rigorously absorbed into the interval remainder -- the
    ``remainder * vol`` path is exercised, not just the exact polynomial part.

    The headline assertion is against the closed form
    ``int int (x+y)^4 = 64 a^6 / 15`` (only the even-even terms of the binomial
    expansion survive the symmetric cell), so it needs no tolerance. The grid and
    Monte-Carlo estimates are approximations carrying their own error, so they are
    widened into reference *intervals* -- the error budget goes on the reference,
    never on the enclosure under test.
    """
    a = 0.4
    center = [0.0, 0.0]
    radius = [a, a]
    order = 2
    x = TaylorModelMV.coordinate(0, center, radius, order)
    y = TaylorModelMV.coordinate(1, center, radius, order)
    tm = (x + y).pow_int(4)  # order-2 TM of (x+y)^4 -> non-trivial remainder
    di = tm.definite_integral()

    def g(px: float, py: float) -> float:
        return (px + py) ** 4

    # dense deterministic midpoint grid
    n = 120
    h = 2.0 * a / n
    axis = [-a + h * (k + 0.5) for k in range(n)]
    grid = h * h * sum(g(px, py) for px in axis for py in axis)

    # random-sample Monte-Carlo
    rng = random.Random(0)
    samples = 200_000
    vol = (2.0 * a) ** 2
    mc = vol * sum(g(rng.uniform(-a, a), rng.uniform(-a, a)) for _ in range(samples)) / samples

    exact = 64.0 * a**6 / 15.0
    assert_encloses(di, exact, what="int int (x+y)^4")

    # Each estimate's error budget is derived, not guessed, so it is a statement about
    # the estimate rather than a concession on the enclosure. Composite midpoint:
    # E ~ (h^2/24) int (f_xx + f_yy); here f_xx = f_yy = 12 (x+y)^2 and
    # int (x+y)^2 = 8 a^4 / 3, giving (h^2/24) * 64 a^4. Doubled for the tail.
    quad_err = 2.0 * (h**2 / 24.0) * 64.0 * a**4
    # Monte-Carlo: 5 sigma of the sample mean, sigma^2 = vol^2 Var(g)/samples with
    # Var(g) <= E[g^2] = int (x+y)^8 / vol = (2 a^10 * 256/45) / vol.
    mc_err = 5.0 * vol * ((256.0 / 45.0) * 2.0 * a**10 / vol / samples) ** 0.5
    assert_encloses_interval(di, (grid - quad_err, grid + quad_err), what="midpoint estimate")
    assert_encloses_interval(di, (mc - mc_err, mc + mc_err), what="Monte-Carlo estimate")
    # Both estimates must actually land within their own budget of the closed form,
    # otherwise the checks above would be vacuously wide.
    assert abs(grid - exact) < quad_err, (grid, exact, quad_err)
    assert abs(mc - exact) < mc_err, (mc, exact, mc_err)
    # the enclosure must be non-vacuous
    assert di.width > 0.0
python -m pytest "packages/omnibias-core/tests/test_verified_tm_integral.py::test_mv_definite_integral_sound_vs_grid_and_random" -q
Method implementation
    def definite_integral(self) -> Interval:
        r"""Certified ``\int_{box} f(x)\,dx`` over the whole (symmetric) cell.

        The multivariate generalisation of
        :meth:`omnibias.core.verified.taylor_model.TaylorModel.definite_integral`.
        On the symmetric box ``\prod_i [c_i - r_i, c_i + r_i]`` a monomial
        ``X^\alpha`` integrates to ``\prod_i \int_{-r_i}^{r_i} X_i^{\alpha_i} dX_i``,
        which is ``0`` whenever any ``\alpha_i`` is odd and
        ``\prod_i 2\,r_i^{\alpha_i+1}/(\alpha_i+1)`` otherwise. The remainder
        contributes ``R \cdot \mathrm{vol}`` with ``\mathrm{vol} = \prod_i 2 r_i``,
        since ``\int_{box} e(x)\,dx = \mathrm{vol}\cdot\bar e`` for a mean value
        ``\bar e \in R``. Everything is outward-rounded, so the returned
        :class:`Interval` provably contains the true integral over the box.
        """
        indices = multi_indices(self.dim, self.order)
        acc = Interval.point(0.0)
        for coeff, alpha in zip(self.coeffs, indices, strict=True):
            if coeff.lo == 0.0 and coeff.hi == 0.0:
                continue
            acc = acc + coeff * _box_integral_monomial(alpha, self.radius)
        vol = _box_integral_monomial(tuple(0 for _ in range(self.dim)), self.radius)
        return acc + self.remainder * vol
View source ↗
pow_intmethod
pow_int(self, n: int) -> TaylorModelMV

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

Parameters

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

Returns: TaylorModelMV

Validation & failure cases
  • When n < 0, raises ValueError('Taylor-model powers require n >= 0').
Executed regression · polynomial product encloses pointwise 2d

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_polynomial_product_encloses_pointwise_2d() -> None:
    center, radius = (0.3, -0.2), (0.4, 0.3)
    order = 6
    x = TaylorModelMV.coordinate(0, center, radius, order)
    y = TaylorModelMV.coordinate(1, center, radius, order)
    # f(x, y) = (x^2 + 1) * (y - 2) + x*y
    f = (x.pow_int(2) + 1.0) * (y - 2.0) + x * y
    b = f.bound()
    for xi, yi in _grid(center, radius):
        val = (xi * xi + 1.0) * (yi - 2.0) + xi * yi
        assert b.lo <= val <= b.hi
python -m pytest "packages/omnibias-core/tests/verified/test_taylor_model_mv.py::test_polynomial_product_encloses_pointwise_2d" -q
Method implementation
    def pow_int(self, n: int) -> TaylorModelMV:
        if n < 0:
            raise ValueError("Taylor-model powers require n >= 0")
        result = TaylorModelMV.constant(1.0, self.center, self.radius, self.order)
        base = self
        e = n
        while e > 0:
            if e & 1:
                result = result * base
            e >>= 1
            if e > 0:
                base = base * base
        return result
View source ↗
__repr__method
__repr__(self) -> str

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

Returns: str

Method implementation
    def __repr__(self) -> str:
        return (
            f"TaylorModelMV(center={self.center!r}, radius={self.radius!r}, "
            f"order={self.order}, remainder={self.remainder!r})"
        )
View source ↗
centerattribute
center: tuple[float, ...] = tuple((float(c) for c in center))

Public instance attribute assigned by __init__. The source assignment is center = tuple((float(c) for c in center)); it describes instance state, not a literal constructor default.

View source ↗
radiusattribute
radius: tuple[float, ...] = tuple((float(r) for r in radius))

Public instance attribute assigned by __init__. The source assignment is radius = tuple((float(r) for r in radius)); it describes instance state, not a literal constructor default.

View source ↗
dimattribute
dim = dim

Public instance attribute assigned by __init__. The source assignment is dim = dim; it describes instance state, not a literal constructor default.

View source ↗
orderattribute
order: int = order

Public instance attribute assigned by __init__. The source assignment is order = order; it describes instance state, not a literal constructor default.

View source ↗
coeffsattribute
coeffs: list[Interval] = list(coeffs)

Public instance attribute assigned by __init__. The source assignment is coeffs = list(coeffs); it describes instance state, not a literal constructor default.

View source ↗
remainderattribute
remainder: Interval = remainder

Public instance attribute assigned by __init__. The source assignment is remainder = remainder; it describes instance state, not a literal constructor default.

View source ↗
Read the implementation
class TaylorModelMV:
    """Total-degree-``order`` multivariate Taylor model on a box."""

    __slots__ = ("center", "radius", "dim", "order", "coeffs", "remainder")

    def __init__(
        self,
        center: Sequence[float],
        radius: Sequence[float],
        order: int,
        coeffs: Sequence[Interval],
        remainder: Interval,
    ) -> None:
        dim = len(center)
        if dim < 1:
            raise ValueError("a multivariate Taylor model needs dim >= 1")
        if len(radius) != dim:
            raise ValueError("center and radius must have the same length")
        if order < 0:
            raise ValueError("order must be >= 0")
        if any(r < 0.0 for r in radius):
            raise ValueError("box radii must be non-negative")
        expected = num_multi_indices(dim, order)
        if len(coeffs) != expected:
            raise ValueError(
                f"expected {expected} coefficients for dim={dim}, order={order}, "
                f"got {len(coeffs)}"
            )
        self.center: tuple[float, ...] = tuple(float(c) for c in center)
        self.radius: tuple[float, ...] = tuple(float(r) for r in radius)
        self.dim = dim
        self.order = order
        self.coeffs: list[Interval] = list(coeffs)
        self.remainder = remainder

    # ----- constructors -------------------------------------------------- #
    @classmethod
    def constant(
        cls,
        value: IntervalLike,
        center: Sequence[float],
        radius: Sequence[float],
        order: int,
    ) -> TaylorModelMV:
        """The model of the constant function ``f(x) = value``."""
        n = num_multi_indices(len(center), order)
        coeffs = [Interval.point(0.0) for _ in range(n)]
        coeffs[0] = Interval.from_value(value)
        return cls(center, radius, order, coeffs, Interval.point(0.0))

    @classmethod
    def coordinate(
        cls,
        axis: int,
        center: Sequence[float],
        radius: Sequence[float],
        order: int,
    ) -> TaylorModelMV:
        """The model of the coordinate map ``f(x) = x_axis = c_axis + X_axis``."""
        dim = len(center)
        if not 0 <= axis < dim:
            raise ValueError(f"axis {axis} out of range for dim {dim}")
        if order < 1:
            raise ValueError("coordinate models need order >= 1")
        n = num_multi_indices(dim, order)
        coeffs = [Interval.point(0.0) for _ in range(n)]
        coeffs[0] = Interval.point(float(center[axis]))
        unit = tuple(1 if i == axis else 0 for i in range(dim))
        coeffs[index_position(dim, order)[unit]] = Interval.point(1.0)
        return cls(center, radius, order, coeffs, Interval.point(0.0))

    # ----- helpers ------------------------------------------------------- #
    def _check(self, other: TaylorModelMV) -> None:
        if (
            self.center != other.center
            or self.radius != other.radius
            or self.order != other.order
        ):
            raise ValueError("Taylor models must share the same box and order")

    def _poly_bound(self) -> Interval:
        """Enclosure of the polynomial part only (no remainder), over the box."""
        indices = multi_indices(self.dim, self.order)
        acc = Interval.point(0.0)
        for idx, coeff in zip(indices, self.coeffs, strict=True):
            if coeff.lo == 0.0 and coeff.hi == 0.0:
                continue
            acc = acc + coeff * _box_monomial(idx, self.radius)
        return acc

    def bound(self) -> Interval:
        """Guaranteed enclosure of ``f`` over the whole box."""
        return self._poly_bound() + self.remainder

    def eval(self, delta: Sequence[IntervalLike]) -> Interval:
        r"""Enclosure of ``f(center + delta)`` for ``delta`` in the relative box.

        ``delta`` is given relative to ``center`` (a point or sub-interval per
        axis); each must lie within ``[-r_i, r_i]`` for the enclosure to be
        valid.  Passing the full relative box reproduces :meth:`bound`.
        """
        if len(delta) != self.dim:
            raise ValueError("delta must have one entry per dimension")
        dvals = [Interval.from_value(d) for d in delta]
        indices = multi_indices(self.dim, self.order)
        acc = Interval.point(0.0)
        for idx, coeff in zip(indices, self.coeffs, strict=True):
            if coeff.lo == 0.0 and coeff.hi == 0.0:
                continue
            mono = Interval.point(1.0)
            for axis, power in enumerate(idx):
                if power:
                    mono = mono * dvals[axis].pow_int(power)
            acc = acc + coeff * mono
        return acc + self.remainder

    # ----- arithmetic ---------------------------------------------------- #
    def __add__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV:
        if isinstance(other, TaylorModelMV):
            self._check(other)
            coeffs = [a + b for a, b in zip(self.coeffs, other.coeffs, strict=True)]
            return TaylorModelMV(
                self.center, self.radius, self.order, coeffs,
                self.remainder + other.remainder,
            )
        coeffs = list(self.coeffs)
        coeffs[0] = coeffs[0] + Interval.from_value(other)
        return TaylorModelMV(self.center, self.radius, self.order, coeffs, self.remainder)

    __radd__ = __add__

    def __neg__(self) -> TaylorModelMV:
        return TaylorModelMV(
            self.center, self.radius, self.order,
            [-c for c in self.coeffs], -self.remainder,
        )

    def __sub__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV:
        if isinstance(other, TaylorModelMV):
            return self.__add__(-other)
        return self.__add__(-Interval.from_value(other))

    def __rsub__(self, other: IntervalLike) -> TaylorModelMV:
        return (-self).__add__(Interval.from_value(other))

    def __mul__(self, other: TaylorModelMV | IntervalLike) -> TaylorModelMV:
        if not isinstance(other, TaylorModelMV):
            scal = Interval.from_value(other)
            return TaylorModelMV(
                self.center, self.radius, self.order,
                [c * scal for c in self.coeffs], self.remainder * scal,
            )
        self._check(other)
        indices = multi_indices(self.dim, self.order)
        pos = index_position(self.dim, self.order)
        n = len(self.coeffs)
        low = [Interval.point(0.0) for _ in range(n)]
        high = Interval.point(0.0)
        for ia in range(n):
            a = self.coeffs[ia]
            if a.lo == 0.0 and a.hi == 0.0:
                continue
            alpha = indices[ia]
            for ib in range(n):
                b = other.coeffs[ib]
                if b.lo == 0.0 and b.hi == 0.0:
                    continue
                gamma = tuple(alpha[k] + indices[ib][k] for k in range(self.dim))
                prod = a * b
                if sum(gamma) <= self.order:
                    low[pos[gamma]] = low[pos[gamma]] + prod
                else:
                    high = high + prod * _box_monomial(gamma, self.radius)
        # f*g = P*Q + P*Rg + Q*Rf + Rf*Rg, with the truncated P*Q tail in `high`.
        # Provably-zero remainder terms are skipped: this keeps an exact-polynomial
        # product exactly remainder-free (no spurious subnormal inflation) and is
        # cheaper, while staying rigorous (a [0,0] factor contributes nothing).
        remainder = high
        self_rzero = self.remainder.lo == 0.0 and self.remainder.hi == 0.0
        other_rzero = other.remainder.lo == 0.0 and other.remainder.hi == 0.0
        if not other_rzero:
            remainder = remainder + self._poly_bound() * other.remainder
        if not self_rzero:
            remainder = remainder + other._poly_bound() * self.remainder
        if not self_rzero and not other_rzero:
            remainder = remainder + self.remainder * other.remainder
        return TaylorModelMV(self.center, self.radius, self.order, low, remainder)

    __rmul__ = __mul__

    def antiderivative(self, axis: int) -> TaylorModelMV:
        r"""Rigorous antiderivative along ``axis``: ``F`` with ``d F / d x_axis = f``.

        Integration is the natural *sound* operation on a Taylor model.  The
        polynomial part integrates term-by-term in the relative variable along
        ``axis`` (raising the total degree by one, so the result has order
        ``order + 1``), with the integration constant fixed by ``F = 0`` on the
        slice ``x_axis = center_axis``.  The remainder integrates rigorously to
        ``R \cdot [-r_axis, r_axis]`` (the mean-value enclosure of
        ``\int_0^{X_axis} e\,dt``).
        """
        if not 0 <= axis < self.dim:
            raise ValueError(f"axis {axis} out of range for dim {self.dim}")
        new_order = self.order + 1
        n_new = num_multi_indices(self.dim, new_order)
        pos_new = index_position(self.dim, new_order)
        old_indices = multi_indices(self.dim, self.order)
        new_coeffs = [Interval.point(0.0) for _ in range(n_new)]
        for c, alpha in zip(self.coeffs, old_indices, strict=True):
            if c.lo == 0.0 and c.hi == 0.0:
                continue
            beta = tuple(a + (1 if i == axis else 0) for i, a in enumerate(alpha))
            scale = Interval.from_rational(Fraction(1, alpha[axis] + 1))
            j = pos_new[beta]
            new_coeffs[j] = new_coeffs[j] + c * scale
        r_axis = self.radius[axis]
        rem = self.remainder * _rel_box([r_axis])[0]
        return TaylorModelMV(self.center, self.radius, new_order, new_coeffs, rem)

    def definite_integral(self) -> Interval:
        r"""Certified ``\int_{box} f(x)\,dx`` over the whole (symmetric) cell.

        The multivariate generalisation of
        :meth:`omnibias.core.verified.taylor_model.TaylorModel.definite_integral`.
        On the symmetric box ``\prod_i [c_i - r_i, c_i + r_i]`` a monomial
        ``X^\alpha`` integrates to ``\prod_i \int_{-r_i}^{r_i} X_i^{\alpha_i} dX_i``,
        which is ``0`` whenever any ``\alpha_i`` is odd and
        ``\prod_i 2\,r_i^{\alpha_i+1}/(\alpha_i+1)`` otherwise. The remainder
        contributes ``R \cdot \mathrm{vol}`` with ``\mathrm{vol} = \prod_i 2 r_i``,
        since ``\int_{box} e(x)\,dx = \mathrm{vol}\cdot\bar e`` for a mean value
        ``\bar e \in R``. Everything is outward-rounded, so the returned
        :class:`Interval` provably contains the true integral over the box.
        """
        indices = multi_indices(self.dim, self.order)
        acc = Interval.point(0.0)
        for coeff, alpha in zip(self.coeffs, indices, strict=True):
            if coeff.lo == 0.0 and coeff.hi == 0.0:
                continue
            acc = acc + coeff * _box_integral_monomial(alpha, self.radius)
        vol = _box_integral_monomial(tuple(0 for _ in range(self.dim)), self.radius)
        return acc + self.remainder * vol

    def pow_int(self, n: int) -> TaylorModelMV:
        if n < 0:
            raise ValueError("Taylor-model powers require n >= 0")
        result = TaylorModelMV.constant(1.0, self.center, self.radius, self.order)
        base = self
        e = n
        while e > 0:
            if e & 1:
                result = result * base
            e >>= 1
            if e > 0:
                base = base * base
        return result

    def __repr__(self) -> str:
        return (
            f"TaylorModelMV(center={self.center!r}, radius={self.radius!r}, "
            f"order={self.order}, remainder={self.remainder!r})"
        )
Other public import paths
  • omnibias.core.verified.TaylorModelMV
  • omnibias.core.verified.taylor_model_mv.TaylorModelMV