omnibias.core.cubature
Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.
import omnibias.core.cubatureModule 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.
MomentSystem
omnibias.core.MomentSystemSource ↗class MomentSystemDataclass 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
| Name | Type & default | Contract |
|---|---|---|
degreedataclass field | intRequired | See the operation contract and implementation below. |
measuredataclass field | MeasureNameRequired | See the operation contract and implementation below. |
target_momentsdataclass field | tuple[float, ...]Required | See the operation contract and implementation below. |
intervaldataclass field | tuple[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" -qRegression 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 -qFields & methods
degreefield
degree: intDeclared int field on MomentSystem. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗measurefield
measure: MeasureNameDeclared 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).
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
int(self.degree) < 0, raisesValueError('degree must be >= 0'). - When
len(self.target_moments) < int(self.degree) + 1, raisesValueError('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" -qMethod 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]))lebesguemethod
lebesgue(cls, degree: int, *, interval: tuple[float, float]=(-1.0, 1.0)) -> MomentSystemSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
degreepositional-or-keyword | intRequired | See the operation contract and implementation below. |
intervalkeyword-only | tuple[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" -qMethod 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)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.MomentSystemomnibias.core.cubature.MomentSystem
QuadratureRule
omnibias.core.QuadratureRuleSource ↗class QuadratureRuleDataclass 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
| Name | Type & default | Contract |
|---|---|---|
nodesdataclass field | tuple[float, ...]Required | See the operation contract and implementation below. |
weightsdataclass field | tuple[float, ...]Required | See the operation contract and implementation below. |
degreedataclass field | intRequired | See the operation contract and implementation below. |
functionaldataclass field | FunctionalNameRequired | See the operation contract and implementation below. |
pack_scaledataclass field | float | NoneRequired | See the operation contract and implementation below. |
bias_cancelleddataclass field | boolRequired | See the operation contract and implementation below. |
measuredataclass field | strRequired | See the operation contract and implementation below. |
intervaldataclass field | tuple[float, float]Required | See the operation contract and implementation below. |
pack_basedataclass field | strDefault: '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" -qFields & 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: intDeclared int field on QuadratureRule. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗functionalfield
functional: FunctionalNameDeclared 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 | NoneDeclared 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: boolDeclared bool field on QuadratureRule. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗measurefield
measure: strDeclared 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'.
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
len(nodes) != len(weights) or not nodes, raisesValueError('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" -qMethod 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)n_nodesproperty
n_nodes(self) -> intSee 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" -qMethod implementation
def n_nodes(self) -> int:
return len(self.nodes)apply_monomialmethod
apply_monomial(self, power: int) -> floatRule applied to x^power (pack moments when functional='pack').
Parameters
| Name | Type & default | Contract |
|---|---|---|
powerpositional-or-keyword | intRequired | See 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" -qMethod 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 accapplymethod
apply(self, values: Sequence[float]) -> floatSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
Returns: float
Validation & failure cases
- When
len(values) != self.n_nodes, raisesValueError('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" -qMethod 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)))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.QuadratureRuleomnibias.core.cubature.QuadratureRule
apply_rule
omnibias.core.apply_ruleSource ↗apply_rule(rule: QuadratureRule, fn: Callable[[float], float]) -> floatThe module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
rulepositional-or-keyword | QuadratureRuleRequired | See the operation contract and implementation below. |
fnpositional-or-keyword | Callable[[float], float]Required | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
rule.functional != 'point', raisesValueError('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" -qRegression 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 -qRead 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_ruleomnibias.core.cubature.apply_rule
certified_error
omnibias.core.certified_errorSource ↗certified_error(rule: QuadratureRule, *, deriv_bound: Interval | None, degree: int) -> IntervalSound enclosure of the quadrature error. Refuses without deriv_bound.
Parameters
| Name | Type & default | Contract |
|---|---|---|
rulepositional-or-keyword | QuadratureRuleRequired | See the operation contract and implementation below. |
deriv_boundkeyword-only | Interval | NoneRequired | See the operation contract and implementation below. |
degreekeyword-only | intRequired | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
deriv_bound is None, raisesValueError('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" -qRegression 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 -qRead 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_erroromnibias.core.cubature.certified_error
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)) -> QuadratureRuleSymmetric 2-node design: keep mass exact, fit the family (not generic GL).
Parameters
| Name | Type & default | Contract |
|---|---|---|
integrandspositional-or-keyword | Sequence[Callable[[float], float]]Required | See the operation contract and implementation below. |
exactspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
nodeskeyword-only | intDefault: 2 | See the operation contract and implementation below. |
intervalkeyword-only | tuple[float, float]Default: (-1.0, 1.0) | See the operation contract and implementation below. |
QuadratureRuleExplicit validation & failure cases
- When
int(nodes) != 2, raisesValueError('design_rule smoke path is the symmetric 2-node rule'). - When
len(integrands) != len(exacts) or not integrands, raisesValueError('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" -qRead 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_ruleomnibias.core.cubature.design_rule
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
| Name | Type & default | Contract |
|---|---|---|
nodes_per_axiskeyword-only | intDefault: 8 | See the operation contract and implementation below. |
max_dimkeyword-only | intDefault: 8 | See the operation contract and implementation below. |
tuple[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" -qRead 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))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.
dict[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" -qRead 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,
}pack_moment
omnibias.core.pack_momentSource ↗pack_moment(pack: PackSpec, j: int, *, scale: float, base: str='gaussian') -> floatClosed-form raw moment of a width-scale pack. Reuses 01-05.
Parameters
| Name | Type & default | Contract |
|---|---|---|
packpositional-or-keyword | PackSpecRequired | See the operation contract and implementation below. |
jpositional-or-keyword | intRequired | See the operation contract and implementation below. |
scalekeyword-only | floatRequired | See the operation contract and implementation below. |
basekeyword-only | strDefault: 'gaussian' | See the operation contract and implementation below. |
floatExecuted 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" -qRead 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_momentomnibias.core.cubature.pack_moment
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
| Name | Type & default | Contract |
|---|---|---|
rulepositional-or-keyword | QuadratureRuleRequired | See the operation contract and implementation below. |
degreekeyword-only | intRequired | See the operation contract and implementation below. |
Callable[[float], float]Explicit validation & failure cases
- When
int(degree) < 0, raisesValueError('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" -qRead 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 kernelOther public import paths
omnibias.core.peano_kernelomnibias.core.cubature.peano_kernel
peano_l1_bound
omnibias.core.cubature.peano_l1_boundSource ↗peano_l1_bound(rule: QuadratureRule, *, degree: int, panels: int=2048) -> IntervalSound enclosure of ||K_d||_1 via Lipschitz panels.
Parameters
| Name | Type & default | Contract |
|---|---|---|
rulepositional-or-keyword | QuadratureRuleRequired | See the operation contract and implementation below. |
degreekeyword-only | intRequired | See the operation contract and implementation below. |
panelskeyword-only | intDefault: 2048 | See the operation contract and implementation below. |
IntervalExecuted 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" -qRead 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 accsolve_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) -> QuadratureRuleSolve 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
| Name | Type & default | Contract |
|---|---|---|
systempositional-or-keyword | MomentSystemRequired | See the operation contract and implementation below. |
nodeskeyword-only | intRequired | See the operation contract and implementation below. |
free_nodeskeyword-only | boolDefault: True | See the operation contract and implementation below. |
functionalkeyword-only | FunctionalNameDefault: 'point' | See the operation contract and implementation below. |
pack_scalekeyword-only | float | NoneDefault: None | See the operation contract and implementation below. |
pack_basekeyword-only | strDefault: 'gaussian' | See the operation contract and implementation below. |
fixed_nodeskeyword-only | Sequence[float] | NoneDefault: None | See the operation contract and implementation below. |
QuadratureRuleExplicit validation & failure cases
- When
n < 1, raisesValueError('nodes must be >= 1'). - When
pack_scale is None or float(pack_scale) <= 0.0, raisesValueError('pack functionals need pack_scale > 0'). - When
xs.size != n, raisesValueError('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" -qRegression 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 -qRead 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_ruleomnibias.core.cubature.solve_rule
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
| Name | Type & default | Contract |
|---|---|---|
degreekeyword-only | intRequired | See the operation contract and implementation below. |
measurekeyword-only | MeasureNameDefault: 'lebesgue' | See the operation contract and implementation below. |
intervalkeyword-only | tuple[float, float]Default: (-1.0, 1.0) | See the operation contract and implementation below. |
customkeyword-only | tuple[float, ...] | NoneDefault: None | See the operation contract and implementation below. |
tuple[float, ...]Explicit validation & failure cases
- When
int(degree) < 0, raisesValueError('degree must be >= 0'). - When
custom is None or len(custom) < int(degree) + 1, raisesValueError('custom moments must cover 0 .. degree'). - When
not lo < hi, raisesValueError('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" -qRead 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_momentsomnibias.core.cubature.target_moments
tensor_product_cost
omnibias.core.cubature.tensor_product_costSource ↗tensor_product_cost(*, nodes_per_axis: int, dim: int) -> intn^D node count. Non-product cubature is out of scope.
Parameters
| Name | Type & default | Contract |
|---|---|---|
nodes_per_axiskeyword-only | intRequired | See the operation contract and implementation below. |
dimkeyword-only | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
int(nodes_per_axis) < 1 or int(dim) < 1, raisesValueError('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" -qRead 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))