Skip to main content

omnibias.core.cubature

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

Neural quadrature / cubature from pack moments (theory 03-06).

A pack's moments are closed form under the founding bias collapse (delta -> 0). Temperature collapse (beta -> inf, feasibility) does not appear. Do not conflate the two. The moment residual is solved, not table-looked-up; Peano error is a sound enclosure when a bound on f^(d+1) is supplied and is refused otherwise. Non-product cubature in high dimension is out of scope.

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

MomentSystem​

omnibias.core.MomentSystemSource ↗
class MomentSystem

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

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
degreedataclass fieldintRequiredSee the operation contract and implementation below.
measuredataclass fieldMeasureNameRequiredSee the operation contract and implementation below.
target_momentsdataclass fieldtuple[float, ...]RequiredSee the operation contract and implementation below.
intervaldataclass fieldtuple[float, float]Default: (-1.0, 1.0)See the operation contract and implementation below.
Executed regression · integrate certified refuses

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_integrate_certified_refuses() -> None:
    rule = solve_rule(MomentSystem.lebesgue(4), nodes=2, free_nodes=True)
    with pytest.raises(ValueError, match="refuses"):
        integrate_certified([0.0, 0.0], rule, deriv_bound=None)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_refuses" -q
Regression example · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest packages/omnibias-fields/tests/_core/test_integrate_certified.py -k test_integrate_certified_contains_x4 -q

Fields & methods

degreefield
degree: int

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

View source ↗
measurefield
measure: MeasureName

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

View source ↗
target_momentsfield
target_moments: tuple[float, ...]

Declared tuple[float, ...] field on MomentSystem. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
intervalfield
interval: tuple[float, float] = (-1.0, 1.0)

Declared tuple[float, float] field on MomentSystem. Default expression: (-1.0, 1.0).

View source ↗
__post_init__method
__post_init__(self) -> None

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

Returns: None

Validation & failure cases
  • When int(self.degree) < 0, raises ValueError('degree must be >= 0').
  • When len(self.target_moments) < int(self.degree) + 1, raises ValueError('target_moments must cover 0 .. degree').
Executed regression · integrate certified refuses

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_integrate_certified_refuses() -> None:
    rule = solve_rule(MomentSystem.lebesgue(4), nodes=2, free_nodes=True)
    with pytest.raises(ValueError, match="refuses"):
        integrate_certified([0.0, 0.0], rule, deriv_bound=None)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_refuses" -q
Method implementation
    def __post_init__(self) -> None:
        if int(self.degree) < 0:
            raise ValueError("degree must be >= 0")
        if len(self.target_moments) < int(self.degree) + 1:
            raise ValueError("target_moments must cover 0 .. degree")
        object.__setattr__(self, "degree", int(self.degree))
        object.__setattr__(self, "target_moments", tuple(float(m) for m in self.target_moments[: self.degree + 1]))
View source ↗
lebesguemethod
lebesgue(cls, degree: int, *, interval: tuple[float, float]=(-1.0, 1.0)) -> MomentSystem

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

Parameters

NameType & defaultContract
degreepositional-or-keywordintRequiredSee the operation contract and implementation below.
intervalkeyword-onlytuple[float, float]Default: (-1.0, 1.0)See the operation contract and implementation below.

Returns: MomentSystem

Executed regression · integrate certified refuses

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_integrate_certified_refuses() -> None:
    rule = solve_rule(MomentSystem.lebesgue(4), nodes=2, free_nodes=True)
    with pytest.raises(ValueError, match="refuses"):
        integrate_certified([0.0, 0.0], rule, deriv_bound=None)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_refuses" -q
Method implementation
    def lebesgue(cls, degree: int, *, interval: tuple[float, float] = (-1.0, 1.0)) -> MomentSystem:
        return cls(degree, "lebesgue", target_moments(degree=degree, measure="lebesgue", interval=interval), interval)
View source ↗
Read the implementation
class MomentSystem:
    degree: int
    measure: MeasureName
    target_moments: tuple[float, ...]
    interval: tuple[float, float] = (-1.0, 1.0)

    def __post_init__(self) -> None:
        if int(self.degree) < 0:
            raise ValueError("degree must be >= 0")
        if len(self.target_moments) < int(self.degree) + 1:
            raise ValueError("target_moments must cover 0 .. degree")
        object.__setattr__(self, "degree", int(self.degree))
        object.__setattr__(self, "target_moments", tuple(float(m) for m in self.target_moments[: self.degree + 1]))

    @classmethod
    def lebesgue(cls, degree: int, *, interval: tuple[float, float] = (-1.0, 1.0)) -> MomentSystem:
        return cls(degree, "lebesgue", target_moments(degree=degree, measure="lebesgue", interval=interval), interval)
Other public import paths
  • omnibias.core.MomentSystem
  • omnibias.core.cubature.MomentSystem
CLASS

QuadratureRule​

omnibias.core.QuadratureRuleSource ↗
class QuadratureRule

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

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
nodesdataclass fieldtuple[float, ...]RequiredSee the operation contract and implementation below.
weightsdataclass fieldtuple[float, ...]RequiredSee the operation contract and implementation below.
degreedataclass fieldintRequiredSee the operation contract and implementation below.
functionaldataclass fieldFunctionalNameRequiredSee the operation contract and implementation below.
pack_scaledataclass fieldfloat | NoneRequiredSee the operation contract and implementation below.
bias_cancelleddataclass fieldboolRequiredSee the operation contract and implementation below.
measuredataclass fieldstrRequiredSee the operation contract and implementation below.
intervaldataclass fieldtuple[float, float]RequiredSee the operation contract and implementation below.
pack_basedataclass fieldstrDefault: 'gaussian'See the operation contract and implementation below.
Executed regression · integrate certified refuses

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_integrate_certified_refuses() -> None:
    rule = solve_rule(MomentSystem.lebesgue(4), nodes=2, free_nodes=True)
    with pytest.raises(ValueError, match="refuses"):
        integrate_certified([0.0, 0.0], rule, deriv_bound=None)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_refuses" -q

Fields & methods

nodesfield
nodes: tuple[float, ...]

Declared tuple[float, ...] field on QuadratureRule. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
weightsfield
weights: tuple[float, ...]

Declared tuple[float, ...] field on QuadratureRule. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
degreefield
degree: int

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

View source ↗
functionalfield
functional: FunctionalName

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

View source ↗
pack_scalefield
pack_scale: float | None

Declared float | None field on QuadratureRule. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
bias_cancelledfield
bias_cancelled: bool

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

View source ↗
measurefield
measure: str

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

View source ↗
intervalfield
interval: tuple[float, float]

Declared tuple[float, float] field on QuadratureRule. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
pack_basefield
pack_base: str = 'gaussian'

Declared str field on QuadratureRule. Default expression: 'gaussian'.

View source ↗
__post_init__method
__post_init__(self) -> None

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

Returns: None

Validation & failure cases
  • When len(nodes) != len(weights) or not nodes, raises ValueError('nodes and weights must be nonempty and aligned').
Executed regression · integrate certified refuses

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_integrate_certified_refuses() -> None:
    rule = solve_rule(MomentSystem.lebesgue(4), nodes=2, free_nodes=True)
    with pytest.raises(ValueError, match="refuses"):
        integrate_certified([0.0, 0.0], rule, deriv_bound=None)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_refuses" -q
Method implementation
    def __post_init__(self) -> None:
        nodes = tuple(float(x) for x in self.nodes)
        weights = tuple(float(w) for w in self.weights)
        if len(nodes) != len(weights) or not nodes:
            raise ValueError("nodes and weights must be nonempty and aligned")
        object.__setattr__(self, "nodes", nodes)
        object.__setattr__(self, "weights", weights)
View source ↗
n_nodesproperty
n_nodes(self) -> int

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

Returns: int

Executed regression · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_contains_x4" -q
Method implementation
    def n_nodes(self) -> int:
        return len(self.nodes)
View source ↗
apply_monomialmethod
apply_monomial(self, power: int) -> float

Rule applied to x^power (pack moments when functional='pack').

Parameters

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

Returns: float

Executed regression · g2 moment exactness point and pack

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

def test_g2_moment_exactness_point_and_pack() -> None:
    system = MomentSystem.lebesgue(8)
    rule = solve_rule(system, nodes=3, free_nodes=True)
    for j in range(rule.degree + 1):
        got = rule.apply_monomial(j)
        exact = system.target_moments[j]
        assert abs(got - exact) <= 1e-13 * max(1.0, abs(exact)), (j, got, exact)
    pack = solve_rule(system, nodes=2, free_nodes=True, functional="pack", pack_scale=0.1, pack_base="gaussian")
    assert pack.bias_cancelled
    for j in (0, 2):
        got = pack.apply_monomial(j)
        exact = system.target_moments[j]
        assert abs(got - exact) <= 1e-13 * max(1.0, abs(exact)), (j, got, exact)
    # Uncorrected GL nodes with the same bump miss m2 by ~2 var.
    var = pack_moment(PackSpec(order=0, mean=0.0), 2, scale=0.1, base="gaussian")
    assert var == pytest.approx(0.01, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_cubature.py::test_g2_moment_exactness_point_and_pack" -q
Method implementation
    def apply_monomial(self, power: int) -> float:
        """Rule applied to ``x^power`` (pack moments when ``functional='pack'``)."""
        acc = 0.0
        for x, w in zip(self.nodes, self.weights, strict=True):
            if self.functional == "point":
                acc += w * (x**power)
            else:
                acc += w * pack_moment(
                    PackSpec(order=0, mean=x),
                    power,
                    scale=float(self.pack_scale or 1.0),
                    base=self.pack_base,
                )
        return acc
View source ↗
applymethod
apply(self, values: Sequence[float]) -> float

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

Parameters

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

Returns: float

Validation & failure cases
  • When len(values) != self.n_nodes, raises ValueError('values must match nodes').
Executed regression · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_contains_x4" -q
Method implementation
    def apply(self, values: Sequence[float]) -> float:
        if len(values) != self.n_nodes:
            raise ValueError("values must match nodes")
        return float(sum(w * float(v) for w, v in zip(self.weights, values, strict=True)))
View source ↗
Read the implementation
class QuadratureRule:
    nodes: tuple[float, ...]
    weights: tuple[float, ...]
    degree: int
    functional: FunctionalName
    pack_scale: float | None
    bias_cancelled: bool
    measure: str
    interval: tuple[float, float]
    pack_base: str = "gaussian"

    def __post_init__(self) -> None:
        nodes = tuple(float(x) for x in self.nodes)
        weights = tuple(float(w) for w in self.weights)
        if len(nodes) != len(weights) or not nodes:
            raise ValueError("nodes and weights must be nonempty and aligned")
        object.__setattr__(self, "nodes", nodes)
        object.__setattr__(self, "weights", weights)

    @property
    def n_nodes(self) -> int:
        return len(self.nodes)

    def apply_monomial(self, power: int) -> float:
        """Rule applied to ``x^power`` (pack moments when ``functional='pack'``)."""
        acc = 0.0
        for x, w in zip(self.nodes, self.weights, strict=True):
            if self.functional == "point":
                acc += w * (x**power)
            else:
                acc += w * pack_moment(
                    PackSpec(order=0, mean=x),
                    power,
                    scale=float(self.pack_scale or 1.0),
                    base=self.pack_base,
                )
        return acc

    def apply(self, values: Sequence[float]) -> float:
        if len(values) != self.n_nodes:
            raise ValueError("values must match nodes")
        return float(sum(w * float(v) for w, v in zip(self.weights, values, strict=True)))
Other public import paths
  • omnibias.core.QuadratureRule
  • omnibias.core.cubature.QuadratureRule
FUNCTION

apply_rule​

omnibias.core.apply_ruleSource ↗
apply_rule(rule: QuadratureRule, fn: Callable[[float], float]) -> float

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
rulepositional-or-keywordQuadratureRuleRequiredSee the operation contract and implementation below.
fnpositional-or-keywordCallable[[float], float]RequiredSee the operation contract and implementation below.
Returnsfloat
Explicit validation & failure cases
  • When rule.functional != 'point', raises ValueError('apply_rule on pack functionals is only closed-form on monomials').

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

Executed regression · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_contains_x4" -q
Regression example · g3 certified error sound and attained

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_g3_certified_error_sound_and_attained() -> None:
    system = MomentSystem.lebesgue(6)
    rule = solve_rule(system, nodes=2, free_nodes=True)
    exact = 2.0 / 5.0
    got = apply_rule(rule, lambda x: x**4)
    true_err = got - exact
    assert abs(true_err + 0.1777777777777778) < 1e-12 or abs(true_err - 0.1777777777777778) < 1e-12
    bound = Interval.point(24.0)
    enc = certified_error(rule, deriv_bound=bound, degree=3)
    assert enc.contains(true_err)
    assert enc.contains(-true_err)
    # Attained to within a small factor on the extremal constant-f^(4) case.
    assert abs(true_err) >= 0.4 * enc.mag
    with pytest.raises(ValueError, match="refuses"):
        certified_error(rule, deriv_bound=None, degree=3)
python -m pytest packages/omnibias-core/tests/test_cubature.py -k test_g3_certified_error_sound_and_attained -q
Read the implementation
def apply_rule(rule: QuadratureRule, fn: Callable[[float], float]) -> float:
    if rule.functional != "point":
        raise ValueError("apply_rule on pack functionals is only closed-form on monomials")
    return float(sum(w * float(fn(x)) for x, w in zip(rule.nodes, rule.weights, strict=True)))
Other public import paths
  • omnibias.core.apply_rule
  • omnibias.core.cubature.apply_rule
FUNCTION

certified_error​

omnibias.core.certified_errorSource ↗
certified_error(rule: QuadratureRule, *, deriv_bound: Interval | None, degree: int) -> Interval

Sound enclosure of the quadrature error. Refuses without deriv_bound.

Parameters

NameType & defaultContract
rulepositional-or-keywordQuadratureRuleRequiredSee the operation contract and implementation below.
deriv_boundkeyword-onlyInterval | NoneRequiredSee the operation contract and implementation below.
degreekeyword-onlyintRequiredSee the operation contract and implementation below.
ReturnsInterval
Explicit validation & failure cases
  • When deriv_bound is None, raises ValueError('certified_error refuses without a bound on f^(d+1)').

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

Executed regression · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_contains_x4" -q
Regression example · g3 certified error sound and attained

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_g3_certified_error_sound_and_attained() -> None:
    system = MomentSystem.lebesgue(6)
    rule = solve_rule(system, nodes=2, free_nodes=True)
    exact = 2.0 / 5.0
    got = apply_rule(rule, lambda x: x**4)
    true_err = got - exact
    assert abs(true_err + 0.1777777777777778) < 1e-12 or abs(true_err - 0.1777777777777778) < 1e-12
    bound = Interval.point(24.0)
    enc = certified_error(rule, deriv_bound=bound, degree=3)
    assert enc.contains(true_err)
    assert enc.contains(-true_err)
    # Attained to within a small factor on the extremal constant-f^(4) case.
    assert abs(true_err) >= 0.4 * enc.mag
    with pytest.raises(ValueError, match="refuses"):
        certified_error(rule, deriv_bound=None, degree=3)
python -m pytest packages/omnibias-core/tests/test_cubature.py -k test_g3_certified_error_sound_and_attained -q
Read the implementation
def certified_error(rule: QuadratureRule, *, deriv_bound: Interval | None, degree: int) -> Interval:
    """Sound enclosure of the quadrature error. Refuses without ``deriv_bound``."""
    if deriv_bound is None:
        raise ValueError("certified_error refuses without a bound on f^(d+1)")
    l1 = peano_l1_bound(rule, degree=int(degree))
    mag = Interval.from_value(deriv_bound.mag)
    radius = l1 * mag
    return Interval(-radius.hi, radius.hi)
Other public import paths
  • omnibias.core.certified_error
  • omnibias.core.cubature.certified_error
FUNCTION

design_rule​

omnibias.core.design_ruleSource ↗
design_rule(integrands: Sequence[Callable[[float], float]], exacts: Sequence[float], *, nodes: int=2, interval: tuple[float, float]=(-1.0, 1.0)) -> QuadratureRule

Symmetric 2-node design: keep mass exact, fit the family (not generic GL).

Parameters

NameType & defaultContract
integrandspositional-or-keywordSequence[Callable[[float], float]]RequiredSee the operation contract and implementation below.
exactspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
nodeskeyword-onlyintDefault: 2See the operation contract and implementation below.
intervalkeyword-onlytuple[float, float]Default: (-1.0, 1.0)See the operation contract and implementation below.
ReturnsQuadratureRule
Explicit validation & failure cases
  • When int(nodes) != 2, raises ValueError('design_rule smoke path is the symmetric 2-node rule').
  • When len(integrands) != len(exacts) or not integrands, raises ValueError('integrands and exacts must align').

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

Executed regression · g4 design win

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_g4_design_win() -> None:
    def family(a: float) -> tuple[object, float]:
        def fn(x: float, coeff: float = a) -> float:
            return x**4 + coeff * x**6

        return fn, 2.0 / 5.0 + a * (2.0 / 7.0)

    seeds = (0.05, 0.07, 0.09, 0.11, 0.13)
    gl = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    integrands = []
    exacts = []
    for a in seeds:
        fn, exact = family(a)
        integrands.append(fn)
        exacts.append(exact)
    designed = design_rule(integrands, exacts, nodes=2)
    ratios = []
    for fn, exact in zip(integrands, exacts, strict=True):
        e_gl = abs(apply_rule(gl, fn) - exact)
        e_des = abs(apply_rule(designed, fn) - exact)
        ratios.append(e_gl / max(e_des, 1e-18))
    assert float(np.mean(ratios)) >= 10.0
    assert all(r > 1.0 for r in ratios)
python -m pytest "packages/omnibias-core/tests/test_cubature.py::test_g4_design_win" -q
Read the implementation
def design_rule(
    integrands: Sequence[Callable[[float], float]],
    exacts: Sequence[float],
    *,
    nodes: int = 2,
    interval: tuple[float, float] = (-1.0, 1.0),
) -> QuadratureRule:
    """Symmetric 2-node design: keep mass exact, fit the family (not generic GL)."""
    if int(nodes) != 2:
        raise ValueError("design_rule smoke path is the symmetric 2-node rule")
    if len(integrands) != len(exacts) or not integrands:
        raise ValueError("integrands and exacts must align")
    lo, hi = interval
    mass = hi - lo
    # Grid-search x0 in (0, 1) to minimize L2 error on the family.
    best_x = math.sqrt(1.0 / 3.0)
    best_err = float("inf")
    for x0 in np.linspace(0.35, 0.95, 121):
        w = 0.5 * mass
        trial = QuadratureRule(
            nodes=(-float(x0), float(x0)),
            weights=(w, w),
            degree=1,
            functional="point",
            pack_scale=None,
            bias_cancelled=False,
            measure="designed",
            interval=interval,
        )
        err = 0.0
        for fn, exact in zip(integrands, exacts, strict=True):
            err += (apply_rule(trial, fn) - float(exact)) ** 2
        if err < best_err:
            best_err = err
            best_x = float(x0)
    w = 0.5 * mass
    return QuadratureRule(
        nodes=(-best_x, best_x),
        weights=(w, w),
        degree=1,
        functional="point",
        pack_scale=None,
        bias_cancelled=False,
        measure="designed",
        interval=interval,
    )
Other public import paths
  • omnibias.core.design_rule
  • omnibias.core.cubature.design_rule
FUNCTION

dimension_scaling_table​

omnibias.core.cubature.dimension_scaling_tableSource ↗
dimension_scaling_table(*, nodes_per_axis: int=8, max_dim: int=8) -> tuple[tuple[int, int], ...]

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
nodes_per_axiskeyword-onlyintDefault: 8See the operation contract and implementation below.
max_dimkeyword-onlyintDefault: 8See the operation contract and implementation below.
Returnstuple[tuple[int, int], ...]
Executed regression · g5 honest scope

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_g5_honest_scope() -> None:
    table = dimension_scaling_table(nodes_per_axis=8, max_dim=6)
    assert table[0] == (1, 8)
    assert table[3] == (4, 8**4)
    # Tensor product is prohibitive once n^D exceeds 4096 at this n.
    prohibitive = min(d for d, cost in table if cost > 4096)
    assert prohibitive == 5
    assert tensor_product_cost(nodes_per_axis=8, dim=5) == 32768
    payload = honesty_payload()
    assert payload["non_product_cubature"] is False
    assert payload["temperature_collapse"] is False
    root = Path(__file__).resolve().parents[1] / "src" / "omnibias" / "core" / "cubature.py"
    text = root.read_text(encoding="utf-8")
    assert "founding bias collapse" in text
    assert "delta -> 0" in text
    assert "beta -> inf" in text
    assert "feasibility" in text
    assert "do not conflate" in text.lower()
python -m pytest "packages/omnibias-core/tests/test_cubature.py::test_g5_honest_scope" -q
Read the implementation
def dimension_scaling_table(*, nodes_per_axis: int = 8, max_dim: int = 8) -> tuple[tuple[int, int], ...]:
    return tuple((d, tensor_product_cost(nodes_per_axis=nodes_per_axis, dim=d)) for d in range(1, int(max_dim) + 1))
FUNCTION

honesty_payload​

omnibias.core.cubature.honesty_payloadSource ↗
honesty_payload() -> dict[str, bool]

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Returnsdict[str, bool]
Executed regression · g5 honest scope

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_g5_honest_scope() -> None:
    table = dimension_scaling_table(nodes_per_axis=8, max_dim=6)
    assert table[0] == (1, 8)
    assert table[3] == (4, 8**4)
    # Tensor product is prohibitive once n^D exceeds 4096 at this n.
    prohibitive = min(d for d, cost in table if cost > 4096)
    assert prohibitive == 5
    assert tensor_product_cost(nodes_per_axis=8, dim=5) == 32768
    payload = honesty_payload()
    assert payload["non_product_cubature"] is False
    assert payload["temperature_collapse"] is False
    root = Path(__file__).resolve().parents[1] / "src" / "omnibias" / "core" / "cubature.py"
    text = root.read_text(encoding="utf-8")
    assert "founding bias collapse" in text
    assert "delta -> 0" in text
    assert "beta -> inf" in text
    assert "feasibility" in text
    assert "do not conflate" in text.lower()
python -m pytest "packages/omnibias-core/tests/test_cubature.py::test_g5_honest_scope" -q
Read the implementation
def honesty_payload() -> dict[str, bool]:
    return {
        "founding_bias_collapse": True,
        "temperature_collapse": False,
        "non_product_cubature": False,
        "smoothing_bias_cancelled": True,
        "refuses_without_deriv_bound": True,
    }
FUNCTION

pack_moment​

omnibias.core.pack_momentSource ↗
pack_moment(pack: PackSpec, j: int, *, scale: float, base: str='gaussian') -> float

Closed-form raw moment of a width-scale pack. Reuses 01-05.

Parameters

NameType & defaultContract
packpositional-or-keywordPackSpecRequiredSee the operation contract and implementation below.
jpositional-or-keywordintRequiredSee the operation contract and implementation below.
scalekeyword-onlyfloatRequiredSee the operation contract and implementation below.
basekeyword-onlystrDefault: 'gaussian'See the operation contract and implementation below.
Returnsfloat
Executed regression · g2 moment exactness point and pack

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

def test_g2_moment_exactness_point_and_pack() -> None:
    system = MomentSystem.lebesgue(8)
    rule = solve_rule(system, nodes=3, free_nodes=True)
    for j in range(rule.degree + 1):
        got = rule.apply_monomial(j)
        exact = system.target_moments[j]
        assert abs(got - exact) <= 1e-13 * max(1.0, abs(exact)), (j, got, exact)
    pack = solve_rule(system, nodes=2, free_nodes=True, functional="pack", pack_scale=0.1, pack_base="gaussian")
    assert pack.bias_cancelled
    for j in (0, 2):
        got = pack.apply_monomial(j)
        exact = system.target_moments[j]
        assert abs(got - exact) <= 1e-13 * max(1.0, abs(exact)), (j, got, exact)
    # Uncorrected GL nodes with the same bump miss m2 by ~2 var.
    var = pack_moment(PackSpec(order=0, mean=0.0), 2, scale=0.1, base="gaussian")
    assert var == pytest.approx(0.01, rel=1e-12)
python -m pytest "packages/omnibias-core/tests/test_cubature.py::test_g2_moment_exactness_point_and_pack" -q
Read the implementation
def pack_moment(pack: PackSpec, j: int, *, scale: float, base: str = "gaussian") -> float:
    """Closed-form raw moment of a width-``scale`` pack. Reuses 01-05."""
    spec = MollifierSpec(base=base, scale=float(scale), packs=(pack,))
    return float(spec.moment(int(j)))
Other public import paths
  • omnibias.core.pack_moment
  • omnibias.core.cubature.pack_moment
FUNCTION

peano_kernel​

omnibias.core.peano_kernelSource ↗
peano_kernel(rule: QuadratureRule, *, degree: int) -> Callable[[float], float]

K_d(t) with E(f) = integral K_d(t) f^{(d+1)}(t) dt.

Parameters

NameType & defaultContract
rulepositional-or-keywordQuadratureRuleRequiredSee the operation contract and implementation below.
degreekeyword-onlyintRequiredSee the operation contract and implementation below.
ReturnsCallable[[float], float]
Explicit validation & failure cases
  • When int(degree) < 0, raises ValueError('degree must be >= 0').

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

Executed regression · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_contains_x4" -q
Read the implementation
def peano_kernel(rule: QuadratureRule, *, degree: int) -> Callable[[float], float]:
    """``K_d(t)`` with ``E(f) = integral K_d(t) f^{(d+1)}(t) dt``."""
    if int(degree) < 0:
        raise ValueError("degree must be >= 0")
    lo, hi = rule.interval
    d = int(degree)
    fact = math.factorial(d)

    def kernel(t: float) -> float:
        # ∫_lo^hi (x-t)_+^d dx
        if t >= hi:
            integral = 0.0
        elif t <= lo:
            integral = ((hi - t) ** (d + 1) - (lo - t) ** (d + 1)) / float(d + 1)
        else:
            integral = ((hi - t) ** (d + 1)) / float(d + 1)
        sample = 0.0
        for x, w in zip(rule.nodes, rule.weights, strict=True):
            sample += w * _plus_power(x, t, d)
        return (integral - sample) / fact

    return kernel
Other public import paths
  • omnibias.core.peano_kernel
  • omnibias.core.cubature.peano_kernel
FUNCTION

peano_l1_bound​

omnibias.core.cubature.peano_l1_boundSource ↗
peano_l1_bound(rule: QuadratureRule, *, degree: int, panels: int=2048) -> Interval

Sound enclosure of ||K_d||_1 via Lipschitz panels.

Parameters

NameType & defaultContract
rulepositional-or-keywordQuadratureRuleRequiredSee the operation contract and implementation below.
degreekeyword-onlyintRequiredSee the operation contract and implementation below.
panelskeyword-onlyintDefault: 2048See the operation contract and implementation below.
ReturnsInterval
Executed regression · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_contains_x4" -q
Read the implementation
def peano_l1_bound(rule: QuadratureRule, *, degree: int, panels: int = 2048) -> Interval:
    """Sound enclosure of ``||K_d||_1`` via Lipschitz panels."""
    kernel = peano_kernel(rule, degree=degree)
    lo, hi = rule.interval
    d = int(degree)
    span = hi - lo
    # |K'| <= (span^d + sum |w| d span^{d-1}) / d!   (crude, sound)
    fact = math.factorial(max(d, 1))
    wabs = sum(abs(w) for w in rule.weights)
    if d == 0:
        lip = 1.0 + wabs
    else:
        lip = (span**d + wabs * float(d) * (span ** (d - 1))) / fact
    h = span / float(panels)
    acc = Interval.point(0.0)
    for i in range(panels):
        a = lo + i * h
        mid = a + 0.5 * h
        km = abs(kernel(mid))
        kmax = km + lip * (0.5 * h)
        acc = acc + Interval.from_value(kmax) * Interval.from_value(h)
    return acc
FUNCTION

solve_rule​

omnibias.core.solve_ruleSource ↗
solve_rule(system: MomentSystem, *, nodes: int, free_nodes: bool=True, functional: FunctionalName='point', pack_scale: float | None=None, pack_base: str='gaussian', fixed_nodes: Sequence[float] | None=None) -> QuadratureRule

Solve a quadrature rule from the moment system.

Point + free nodes is Gauss-type (Golub–Welsch). Point + fixed nodes is Newton–Cotes via the Birkhoff Vandermonde. Pack functionals re-solve so the O(scale^2) bump moment is cancelled.

Parameters

NameType & defaultContract
systempositional-or-keywordMomentSystemRequiredSee the operation contract and implementation below.
nodeskeyword-onlyintRequiredSee the operation contract and implementation below.
free_nodeskeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
functionalkeyword-onlyFunctionalNameDefault: 'point'See the operation contract and implementation below.
pack_scalekeyword-onlyfloat | NoneDefault: NoneSee the operation contract and implementation below.
pack_basekeyword-onlystrDefault: 'gaussian'See the operation contract and implementation below.
fixed_nodeskeyword-onlySequence[float] | NoneDefault: NoneSee the operation contract and implementation below.
ReturnsQuadratureRule
Explicit validation & failure cases
  • When n < 1, raises ValueError('nodes must be >= 1').
  • When pack_scale is None or float(pack_scale) <= 0.0, raises ValueError('pack functionals need pack_scale > 0').
  • When xs.size != n, raises ValueError('fixed_nodes length must match nodes').

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

Executed regression · integrate certified refuses

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_integrate_certified_refuses() -> None:
    rule = solve_rule(MomentSystem.lebesgue(4), nodes=2, free_nodes=True)
    with pytest.raises(ValueError, match="refuses"):
        integrate_certified([0.0, 0.0], rule, deriv_bound=None)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_refuses" -q
Regression example · integrate certified contains x4

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_integrate_certified_contains_x4() -> None:
    rule = solve_rule(MomentSystem.lebesgue(6), nodes=2, free_nodes=True)
    values = [x**4 for x in rule.nodes]
    enc = integrate_certified(values, rule, deriv_bound=Interval.point(24.0), degree=3)
    exact = 0.4
    assert enc.contains(exact)
    main = apply_rule(rule, lambda x: x**4)
    assert enc.contains(main)
python -m pytest packages/omnibias-fields/tests/_core/test_integrate_certified.py -k test_integrate_certified_contains_x4 -q
Read the implementation
def solve_rule(
    system: MomentSystem,
    *,
    nodes: int,
    free_nodes: bool = True,
    functional: FunctionalName = "point",
    pack_scale: float | None = None,
    pack_base: str = "gaussian",
    fixed_nodes: Sequence[float] | None = None,
) -> QuadratureRule:
    """Solve a quadrature rule from the moment system.

    Point + free nodes is Gauss-type (Golub–Welsch). Point + fixed nodes
    is Newton–Cotes via the Birkhoff Vandermonde. Pack functionals
    re-solve so the ``O(scale^2)`` bump moment is cancelled.
    """
    n = int(nodes)
    if n < 1:
        raise ValueError("nodes must be >= 1")
    lo, hi = system.interval
    if functional == "pack":
        if pack_scale is None or float(pack_scale) <= 0.0:
            raise ValueError("pack functionals need pack_scale > 0")
        return _solve_pack_rule(system, n=n, scale=float(pack_scale), base=pack_base, free_nodes=free_nodes)
    need = 2 * n if free_nodes else n
    moms = target_moments(
        degree=max(system.degree, need - 1),
        measure=system.measure,
        interval=system.interval,
        custom=system.target_moments if system.measure == "custom" else None,
    )
    if free_nodes:
        exact = (
            _lebesgue_moments_exact(2 * n - 1, lo, hi)
            if system.measure == "lebesgue"
            else moms
        )
        xs, ws = _golub_welsch(exact, n)
        deg = 2 * n - 1
    else:
        if fixed_nodes is None:
            # Chebyshev extrema on the interval, Newton–Cotes weights.
            if n == 1:
                xs = np.array([0.5 * (lo + hi)], dtype=np.float64)
            else:
                k = np.arange(n, dtype=np.float64)
                t = np.cos(math.pi * k / (n - 1))
                xs = 0.5 * (hi + lo) + 0.5 * (hi - lo) * t
        else:
            xs = np.asarray(fixed_nodes, dtype=np.float64)
            if xs.size != n:
                raise ValueError("fixed_nodes length must match nodes")
        ws = _fixed_node_weights(xs, moms)
        deg = n - 1
    return QuadratureRule(
        nodes=tuple(float(x) for x in xs),
        weights=tuple(float(w) for w in ws),
        degree=deg,
        functional="point",
        pack_scale=None,
        bias_cancelled=False,
        measure=system.measure,
        interval=(lo, hi),
    )
Other public import paths
  • omnibias.core.solve_rule
  • omnibias.core.cubature.solve_rule
FUNCTION

target_moments​

omnibias.core.target_momentsSource ↗
target_moments(*, degree: int, measure: MeasureName='lebesgue', interval: tuple[float, float]=(-1.0, 1.0), custom: tuple[float, ...] | None=None) -> tuple[float, ...]

Moments M_j = integral x^j dmu for j = 0 .. degree.

Parameters

NameType & defaultContract
degreekeyword-onlyintRequiredSee the operation contract and implementation below.
measurekeyword-onlyMeasureNameDefault: 'lebesgue'See the operation contract and implementation below.
intervalkeyword-onlytuple[float, float]Default: (-1.0, 1.0)See the operation contract and implementation below.
customkeyword-onlytuple[float, ...] | NoneDefault: NoneSee the operation contract and implementation below.
Returnstuple[float, ...]
Explicit validation & failure cases
  • When int(degree) < 0, raises ValueError('degree must be >= 0').
  • When custom is None or len(custom) < int(degree) + 1, raises ValueError('custom moments must cover 0 .. degree').
  • When not lo < hi, raises ValueError('interval needs lo < hi').

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

Executed regression · integrate certified refuses

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_integrate_certified_refuses() -> None:
    rule = solve_rule(MomentSystem.lebesgue(4), nodes=2, free_nodes=True)
    with pytest.raises(ValueError, match="refuses"):
        integrate_certified([0.0, 0.0], rule, deriv_bound=None)
python -m pytest "packages/omnibias-fields/tests/_core/test_integrate_certified.py::test_integrate_certified_refuses" -q
Read the implementation
def target_moments(
    *,
    degree: int,
    measure: MeasureName = "lebesgue",
    interval: tuple[float, float] = (-1.0, 1.0),
    custom: tuple[float, ...] | None = None,
) -> tuple[float, ...]:
    """Moments ``M_j = integral x^j dmu`` for ``j = 0 .. degree``."""
    if int(degree) < 0:
        raise ValueError("degree must be >= 0")
    if measure == "custom":
        if custom is None or len(custom) < int(degree) + 1:
            raise ValueError("custom moments must cover 0 .. degree")
        return tuple(float(m) for m in custom[: int(degree) + 1])
    lo, hi = float(interval[0]), float(interval[1])
    if not (lo < hi):
        raise ValueError("interval needs lo < hi")
    out: list[float] = []
    for j in range(int(degree) + 1):
        if measure == "lebesgue":
            out.append((hi ** (j + 1) - lo ** (j + 1)) / float(j + 1))
        elif measure == "gaussian":
            # Standard normal moments on R (interval is ignored).
            if j % 2 == 1:
                out.append(0.0)
            else:
                k = j // 2
                out.append(float(math.factorial(j) // (2**k * math.factorial(k))))
        else:
            raise ValueError(f"unknown measure {measure!r}")
    return tuple(out)
Other public import paths
  • omnibias.core.target_moments
  • omnibias.core.cubature.target_moments
FUNCTION

tensor_product_cost​

omnibias.core.cubature.tensor_product_costSource ↗
tensor_product_cost(*, nodes_per_axis: int, dim: int) -> int

n^D node count. Non-product cubature is out of scope.

Parameters

NameType & defaultContract
nodes_per_axiskeyword-onlyintRequiredSee the operation contract and implementation below.
dimkeyword-onlyintRequiredSee the operation contract and implementation below.
Returnsint
Explicit validation & failure cases
  • When int(nodes_per_axis) < 1 or int(dim) < 1, raises ValueError('nodes_per_axis and dim must be >= 1').

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

Executed regression · g5 honest scope

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_g5_honest_scope() -> None:
    table = dimension_scaling_table(nodes_per_axis=8, max_dim=6)
    assert table[0] == (1, 8)
    assert table[3] == (4, 8**4)
    # Tensor product is prohibitive once n^D exceeds 4096 at this n.
    prohibitive = min(d for d, cost in table if cost > 4096)
    assert prohibitive == 5
    assert tensor_product_cost(nodes_per_axis=8, dim=5) == 32768
    payload = honesty_payload()
    assert payload["non_product_cubature"] is False
    assert payload["temperature_collapse"] is False
    root = Path(__file__).resolve().parents[1] / "src" / "omnibias" / "core" / "cubature.py"
    text = root.read_text(encoding="utf-8")
    assert "founding bias collapse" in text
    assert "delta -> 0" in text
    assert "beta -> inf" in text
    assert "feasibility" in text
    assert "do not conflate" in text.lower()
python -m pytest "packages/omnibias-core/tests/test_cubature.py::test_g5_honest_scope" -q
Read the implementation
def tensor_product_cost(*, nodes_per_axis: int, dim: int) -> int:
    """``n^D`` node count. Non-product cubature is out of scope."""
    if int(nodes_per_axis) < 1 or int(dim) < 1:
        raise ValueError("nodes_per_axis and dim must be >= 1")
    return int(int(nodes_per_axis) ** int(dim))