omnibias.core.mollifier
Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.
import omnibias.core.mollifierModule contract & mathematical conventions
Mollifier / distribution calculus for OMBU packs (theory 01-05).
A collapsing pack is a mollifier: the family phi_eps(u) = (1/eps) phi(u/eps)
converges weakly to a Dirac mass as eps -> 0, and a K-pack converges to
the (K-1)-st distributional derivative of that mass. This is the founding
delta -> 0 register, restated as a test-function generator for weak forms.
Analytic bases are **not** compactly supported. Boundary terms in a weak form
are bounded by a certified exponentially small tail (an Interval),
never assumed zero. Higher-order (moment-annihilating) mollifiers take
**negative** values and are no longer densities.
Pure Python: no tensor imports. Tensor-side test-function assembly lives in
omnibias.fields.weak (theory 02-04).
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.
MollifierSpec
omnibias.core.MollifierSpecSource ↗class MollifierSpecDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A (possibly multi-scale) mollifier built from CDF-type packs.
Parameters
base: Activation name. sigmoid / logistic share the logistic density; tanh / sech share (1/2) sech^2; gaussian is the standard normal density. The founding limit is eps -> 0 (equivalently delta -> 0), not temperature collapse.
scale: Reference width eps > 0. Each pack is evaluated at pack_scales[g] * scale.
packs: PackSpec entries. order is unused for the density itself (keep 0); mean is the physical offset; weight is the outer coefficient. Negative weights are required past order 2 and mean the kernel is no longer a density.
pack_scales: Relative scale per pack (default all 1). Richardson order-4 uses (1, 2) with weights (4/3, -1/3).
Parameters
| Name | Type & default | Contract |
|---|---|---|
basedataclass field | strRequired | Activation name. sigmoid / logistic share the logistic density; tanh / sech share (1/2) sech^2; gaussian is the standard normal density. The founding limit is eps -> 0 (equivalently delta -> 0), not temperature collapse. |
scaledataclass field | floatRequired | Reference width eps > 0. Each pack is evaluated at pack_scales[g] * scale. |
packsdataclass field | tuple[PackSpec, ...]Required | PackSpec entries. order is unused for the density itself (keep 0); mean is the physical offset; weight is the outer coefficient. Negative weights are required past order 2 and mean the kernel is no longer a density. |
pack_scalesdataclass field | tuple[float, ...]Default: () | Relative scale per pack (default all 1). Richardson order-4 uses (1, 2) with weights (4/3, -1/3). |
Executed regression · admissible rejects bad form order
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_admissible_rejects_bad_form_order() -> None:
spec = design_order("gaussian", 2)
with pytest.raises(ValueError, match="form_order"):
is_admissible(spec, form_order=-1)python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_admissible_rejects_bad_form_order" -qRegression example · scaled moments homogeneous
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_scaled_moments_homogeneous() -> None:
spec = MollifierSpec("tanh", 0.1, (PackSpec(0, 0.0),))
m = moments(spec, 2)
assert m[2] == pytest.approx((0.1**2) * (math.pi**2 / 12.0), rel=1e-12)python -m pytest packages/omnibias-core/tests/test_mollifier.py -k test_scaled_moments_homogeneous -qFields & methods
basefield
base: strActivation name. sigmoid / logistic share the logistic density; tanh / sech share (1/2) sech^2; gaussian is the standard normal density. The founding limit is eps -> 0 (equivalently delta -> 0), not temperature collapse.
scalefield
scale: floatReference width eps > 0. Each pack is evaluated at pack_scales[g] * scale.
packsfield
packs: tuple[PackSpec, ...]PackSpec entries. order is unused for the density itself (keep 0); mean is the physical offset; weight is the outer coefficient. Negative weights are required past order 2 and mean the kernel is no longer a density.
pack_scalesfield
pack_scales: tuple[float, ...] = ()Relative scale per pack (default all 1). Richardson order-4 uses (1, 2) with weights (4/3, -1/3).
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
not self.scale > 0.0 or self.scale != self.scale, raisesValueError(f'scale must be finite and positive, got {self.scale}'). - When
not packs, raisesValueError('MollifierSpec requires at least one pack'). - When
len(rel) != len(packs), raisesValueError('pack_scales must match packs'). - When
any((s <= 0.0 or s != s for s in rel)), raisesValueError('pack_scales must be finite and positive').
Executed regression · admissible rejects bad form order
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_admissible_rejects_bad_form_order() -> None:
spec = design_order("gaussian", 2)
with pytest.raises(ValueError, match="form_order"):
is_admissible(spec, form_order=-1)python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_admissible_rejects_bad_form_order" -qMethod implementation
def __post_init__(self) -> None:
name = _canonical_base(self.base)
if not (self.scale > 0.0) or self.scale != self.scale:
raise ValueError(f"scale must be finite and positive, got {self.scale}")
packs = tuple(self.packs)
if not packs:
raise ValueError("MollifierSpec requires at least one pack")
rel = self.pack_scales
if not rel:
rel = tuple(1.0 for _ in packs)
if len(rel) != len(packs):
raise ValueError("pack_scales must match packs")
if any(s <= 0.0 or s != s for s in rel):
raise ValueError("pack_scales must be finite and positive")
object.__setattr__(self, "base", name)
object.__setattr__(self, "scale", float(self.scale))
object.__setattr__(self, "packs", packs)
object.__setattr__(self, "pack_scales", tuple(float(s) for s in rel))familyproperty
family(self) -> strMoment family: gaussian, logistic, or sech.
Returns: str
Executed regression · scaled moments homogeneous
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_scaled_moments_homogeneous() -> None:
spec = MollifierSpec("tanh", 0.1, (PackSpec(0, 0.0),))
m = moments(spec, 2)
assert m[2] == pytest.approx((0.1**2) * (math.pi**2 / 12.0), rel=1e-12)python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_scaled_moments_homogeneous" -qMethod implementation
def family(self) -> str:
"""Moment family: ``gaussian``, ``logistic``, or ``sech``."""
return _family(self.base)orderproperty
order(self) -> intFirst non-vanishing moment index >= 1 (0 if only mass remains).
Returns: int
Executed regression · order2 is positive density
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_order2_is_positive_density() -> None:
spec = design_order("gaussian", 2, scale=1.0)
assert spec.order == 2
assert spec.is_positive is True
assert is_admissible(spec, form_order=2) is Truepython -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_order2_is_positive_density" -qMethod implementation
def order(self) -> int:
"""First non-vanishing moment index ``>= 1`` (``0`` if only mass remains)."""
# Even kernels: scan even indices. Cap at 16 so the property is cheap.
for j in range(1, 17):
if abs(self.moment(j)) > _MOMENT_TOL:
return j
return 0is_positiveproperty
is_positive(self) -> boolFalse once any outer weight is negative (order > 2).
Returns: bool
Executed regression · order2 is positive density
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_order2_is_positive_density() -> None:
spec = design_order("gaussian", 2, scale=1.0)
assert spec.order == 2
assert spec.is_positive is True
assert is_admissible(spec, form_order=2) is Truepython -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_order2_is_positive_density" -qMethod implementation
def is_positive(self) -> bool:
"""``False`` once any outer weight is negative (order ``> 2``)."""
return all(p.weight >= 0.0 for p in self.packs)momentmethod
moment(self, index: int) -> floatRaw moment integral u^{index} psi(u) du of this spec.
Parameters
| Name | Type & default | Contract |
|---|---|---|
indexpositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: float
Executed regression · order2 is positive density
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_order2_is_positive_density() -> None:
spec = design_order("gaussian", 2, scale=1.0)
assert spec.order == 2
assert spec.is_positive is True
assert is_admissible(spec, form_order=2) is Truepython -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_order2_is_positive_density" -qMethod implementation
def moment(self, index: int) -> float:
"""Raw moment ``integral u^{index} psi(u) du`` of this spec."""
return moments(self, up_to=index)[index]Read the implementation
class MollifierSpec:
"""A (possibly multi-scale) mollifier built from CDF-type packs.
Parameters
----------
base:
Activation name. ``sigmoid`` / ``logistic`` share the logistic density;
``tanh`` / ``sech`` share ``(1/2) sech^2``; ``gaussian`` is the standard
normal density. The founding limit is ``eps -> 0`` (equivalently
``delta -> 0``), not temperature collapse.
scale:
Reference width ``eps > 0``. Each pack is evaluated at
``pack_scales[g] * scale``.
packs:
:class:`PackSpec` entries. ``order`` is unused for the density itself
(keep ``0``); ``mean`` is the physical offset; ``weight`` is the outer
coefficient. Negative weights are required past order 2 and mean the
kernel is no longer a density.
pack_scales:
Relative scale per pack (default all ``1``). Richardson order-4 uses
``(1, 2)`` with weights ``(4/3, -1/3)``.
"""
base: str
scale: float
packs: tuple[PackSpec, ...]
pack_scales: tuple[float, ...] = ()
def __post_init__(self) -> None:
name = _canonical_base(self.base)
if not (self.scale > 0.0) or self.scale != self.scale:
raise ValueError(f"scale must be finite and positive, got {self.scale}")
packs = tuple(self.packs)
if not packs:
raise ValueError("MollifierSpec requires at least one pack")
rel = self.pack_scales
if not rel:
rel = tuple(1.0 for _ in packs)
if len(rel) != len(packs):
raise ValueError("pack_scales must match packs")
if any(s <= 0.0 or s != s for s in rel):
raise ValueError("pack_scales must be finite and positive")
object.__setattr__(self, "base", name)
object.__setattr__(self, "scale", float(self.scale))
object.__setattr__(self, "packs", packs)
object.__setattr__(self, "pack_scales", tuple(float(s) for s in rel))
@property
def family(self) -> str:
"""Moment family: ``gaussian``, ``logistic``, or ``sech``."""
return _family(self.base)
@property
def order(self) -> int:
"""First non-vanishing moment index ``>= 1`` (``0`` if only mass remains)."""
# Even kernels: scan even indices. Cap at 16 so the property is cheap.
for j in range(1, 17):
if abs(self.moment(j)) > _MOMENT_TOL:
return j
return 0
@property
def is_positive(self) -> bool:
"""``False`` once any outer weight is negative (order ``> 2``)."""
return all(p.weight >= 0.0 for p in self.packs)
def moment(self, index: int) -> float:
"""Raw moment ``integral u^{index} psi(u) du`` of this spec."""
return moments(self, up_to=index)[index]Other public import paths
omnibias.core.MollifierSpecomnibias.core.mollifier.MollifierSpec
design_order
omnibias.core.design_orderSource ↗design_order(base: str, order: int, *, scale: float=1.0) -> MollifierSpecSolve pack weights that annihilate moments 1 .. order-1.
Even kernels: geometric scales 1, 2, 4, ... and a Vandermonde system
over Q (the same exact-rational discipline as irregular Birkhoff
stencils, implemented here so omnibias.core never imports
omnibias.difference). Order 4 recovers the Richardson pair
(4/3) phi_eps - (1/3) phi_{2 eps}.
Parameters
| Name | Type & default | Contract |
|---|---|---|
basepositional-or-keyword | strRequired | See the operation contract and implementation below. |
orderpositional-or-keyword | intRequired | See the operation contract and implementation below. |
scalekeyword-only | floatDefault: 1.0 | See the operation contract and implementation below. |
MollifierSpecExplicit validation & failure cases
- When
m < 2 or m % 2 == 1, raisesValueError(f'design_order requires even order >= 2, got {order}'). - When
not scale > 0.0 or scale != scale, raisesValueError(f'scale must be finite and positive, got {scale}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · admissible rejects bad form order
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_admissible_rejects_bad_form_order() -> None:
spec = design_order("gaussian", 2)
with pytest.raises(ValueError, match="form_order"):
is_admissible(spec, form_order=-1)python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_admissible_rejects_bad_form_order" -qRegression example · scaled moments homogeneous
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_scaled_moments_homogeneous() -> None:
spec = MollifierSpec("tanh", 0.1, (PackSpec(0, 0.0),))
m = moments(spec, 2)
assert m[2] == pytest.approx((0.1**2) * (math.pi**2 / 12.0), rel=1e-12)python -m pytest packages/omnibias-core/tests/test_mollifier.py -k test_scaled_moments_homogeneous -qRead the implementation
def design_order(base: str, order: int, *, scale: float = 1.0) -> MollifierSpec:
"""Solve pack weights that annihilate moments ``1 .. order-1``.
Even kernels: geometric scales ``1, 2, 4, ...`` and a Vandermonde system
over ``Q`` (the same exact-rational discipline as irregular Birkhoff
stencils, implemented here so ``omnibias.core`` never imports
``omnibias.difference``). Order 4 recovers the Richardson pair
``(4/3) phi_eps - (1/3) phi_{2 eps}``.
"""
_canonical_base(base)
m = int(order)
if m < 2 or m % 2 == 1:
raise ValueError(f"design_order requires even order >= 2, got {order}")
if not (scale > 0.0) or scale != scale:
raise ValueError(f"scale must be finite and positive, got {scale}")
n = m // 2
rel = _relative_scales(n)
# Rows: mass, then even powers 2, 4, ..., 2(n-1).
matrix: list[list[Fraction]] = []
rhs: list[Fraction] = []
for row in range(n):
power = 2 * row
matrix.append([Fraction(rel[i]) ** power for i in range(n)])
rhs.append(Fraction(1) if row == 0 else Fraction(0))
weights = _gauss_elim(matrix, rhs)
packs = tuple(
PackSpec(order=0, mean=0.0, weight=float(w)) for w in weights
)
return MollifierSpec(
base=base,
scale=float(scale),
packs=packs,
pack_scales=tuple(float(s) for s in rel),
)Other public import paths
omnibias.core.design_orderomnibias.core.mollifier.design_order
is_admissible
omnibias.core.is_admissibleSource ↗is_admissible(spec: MollifierSpec, *, form_order: int) -> boolPetrov-Galerkin admissibility: smoothness, decay, known integrals.
Analytic bases are C^infty, so form_order only rejects negatives.
Rapid decay and closed-form antiderivatives are supplied by the family.
This is not a compact-support test.
Parameters
| Name | Type & default | Contract |
|---|---|---|
specpositional-or-keyword | MollifierSpecRequired | See the operation contract and implementation below. |
form_orderkeyword-only | intRequired | See the operation contract and implementation below. |
boolExplicit validation & failure cases
- When
int(form_order) < 0, raisesValueError(f'form_order must be >= 0, got {form_order}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · admissible rejects bad form order
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_admissible_rejects_bad_form_order() -> None:
spec = design_order("gaussian", 2)
with pytest.raises(ValueError, match="form_order"):
is_admissible(spec, form_order=-1)python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_admissible_rejects_bad_form_order" -qRegression example · order2 is positive density
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_order2_is_positive_density() -> None:
spec = design_order("gaussian", 2, scale=1.0)
assert spec.order == 2
assert spec.is_positive is True
assert is_admissible(spec, form_order=2) is Truepython -m pytest packages/omnibias-core/tests/test_mollifier.py -k test_order2_is_positive_density -qRead the implementation
def is_admissible(spec: MollifierSpec, *, form_order: int) -> bool:
"""Petrov-Galerkin admissibility: smoothness, decay, known integrals.
Analytic bases are ``C^infty``, so ``form_order`` only rejects negatives.
Rapid decay and closed-form antiderivatives are supplied by the family.
This is not a compact-support test.
"""
if int(form_order) < 0:
raise ValueError(f"form_order must be >= 0, got {form_order}")
try:
_canonical_base(spec.base)
except ValueError:
return False
return spec.scale > 0.0 and len(spec.packs) > 0Other public import paths
omnibias.core.is_admissibleomnibias.core.mollifier.is_admissible
moments
omnibias.core.momentsSource ↗moments(spec: MollifierSpec, up_to: int) -> tuple[float, ...]Raw moments (M_0, ..., M_{up_to}).
Closed form for gaussian / logistic / sech-type families. Odd unit moments vanish; a non-zero mean expands by the binomial theorem.
Parameters
| Name | Type & default | Contract |
|---|---|---|
specpositional-or-keyword | MollifierSpecRequired | See the operation contract and implementation below. |
up_topositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[float, ...]Explicit validation & failure cases
- When
int(up_to) < 0, raisesValueError(f'up_to must be >= 0, got {up_to}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · scaled moments homogeneous
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_scaled_moments_homogeneous() -> None:
spec = MollifierSpec("tanh", 0.1, (PackSpec(0, 0.0),))
m = moments(spec, 2)
assert m[2] == pytest.approx((0.1**2) * (math.pi**2 / 12.0), rel=1e-12)python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_scaled_moments_homogeneous" -qRegression example · order4 richardson worked example
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_order4_richardson_worked_example() -> None:
"""Spec §5: (4/3) phi_eps - (1/3) phi_{2 eps} kills M_2 and is exact on u^2."""
spec = design_order("tanh", 4, scale=0.1)
assert spec.pack_scales == pytest.approx((1.0, 2.0))
assert spec.packs[0].weight == pytest.approx(4.0 / 3.0)
assert spec.packs[1].weight == pytest.approx(-1.0 / 3.0)
m = moments(spec, 4)
assert m[0] == pytest.approx(1.0, rel=1e-12)
assert abs(m[1]) <= 1e-12
assert abs(m[2]) <= 1e-12
assert abs(m[3]) <= 1e-12
# Convolution against u^2 at 0 is M_2 == 0 (order-4 exact on degree < 4).
assert spec.order == 4
assert spec.is_positive is Falsepython -m pytest packages/omnibias-core/tests/test_mollifier.py -k test_order4_richardson_worked_example -qRead the implementation
def moments(spec: MollifierSpec, up_to: int) -> tuple[float, ...]:
"""Raw moments ``(M_0, ..., M_{up_to})``.
Closed form for gaussian / logistic / sech-type families. Odd unit
moments vanish; a non-zero mean expands by the binomial theorem.
"""
if int(up_to) < 0:
raise ValueError(f"up_to must be >= 0, got {up_to}")
family = spec.family
unit = [_unit_even_moment(family, k) for k in range(up_to + 1)]
out = [0.0] * (up_to + 1)
for pack, rel in zip(spec.packs, spec.pack_scales, strict=True):
s = spec.scale * rel
mu = pack.mean
w = pack.weight
for j in range(up_to + 1):
acc = 0.0
for k in range(j + 1):
acc += float(comb(j, k)) * (s**k) * unit[k] * (mu ** (j - k))
out[j] += w * acc
return tuple(out)Other public import paths
omnibias.core.momentsomnibias.core.mollifier.moments
tail_bound
omnibias.core.tail_boundSource ↗tail_bound(spec: MollifierSpec, *, half_width: float) -> IntervalOutward-rounded enclosure of mass outside [-half_width, half_width].
Analytic bases have exponentially small tails, not compact support. The returned interval is a sound enclosure of the *signed* outside integral (higher-order kernels can be negative). Zero violations means every true value lies inside the interval.
Parameters
| Name | Type & default | Contract |
|---|---|---|
specpositional-or-keyword | MollifierSpecRequired | See the operation contract and implementation below. |
half_widthkeyword-only | floatRequired | See the operation contract and implementation below. |
IntervalExplicit validation & failure cases
- When
not half_width > 0.0 or half_width != half_width, raisesValueError(f'half_width must be finite and positive, got {half_width}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · rejects bad inputs
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_rejects_bad_inputs() -> None:
with pytest.raises(ValueError, match="unsupported"):
MollifierSpec("relu", 1.0, (PackSpec(0, 0.0),))
with pytest.raises(ValueError, match="positive"):
MollifierSpec("tanh", 0.0, (PackSpec(0, 0.0),))
with pytest.raises(ValueError, match="even"):
design_order("tanh", 3)
with pytest.raises(ValueError, match="half_width"):
tail_bound(design_order("tanh", 2), half_width=-1.0)python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_rejects_bad_inputs" -qRegression example · tail bound sound grid and sample
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_tail_bound_sound_grid_and_sample() -> None:
"""G3: Interval contains the true outside mass; zero undercovers."""
rng = random.Random(0)
specs = [
design_order("tanh", 2, scale=0.25),
design_order("sigmoid", 2, scale=0.5),
design_order("gaussian", 2, scale=0.4),
design_order("tanh", 4, scale=0.3),
]
widths = [0.5, 1.0, 1.5, 2.0, 3.0] + [rng.uniform(0.4, 4.0) for _ in range(20)]
violations = 0
n = 0
for spec in specs:
for w in widths:
enclosed = tail_bound(spec, half_width=w)
truth = true_outside_mass(spec, half_width=w)
n += 1
if not enclosed.contains(truth):
violations += 1
assert n >= 100
assert violations == 0python -m pytest packages/omnibias-core/tests/test_mollifier.py -k test_tail_bound_sound_grid_and_sample -qRead the implementation
def tail_bound(spec: MollifierSpec, *, half_width: float) -> Interval:
"""Outward-rounded enclosure of mass outside ``[-half_width, half_width]``.
Analytic bases have exponentially small tails, not compact support. The
returned interval is a sound enclosure of the *signed* outside integral
(higher-order kernels can be negative). Zero violations means every true
value lies inside the interval.
"""
if not (half_width > 0.0) or half_width != half_width:
raise ValueError(f"half_width must be finite and positive, got {half_width}")
family = spec.family
total = Interval.from_rational(0)
for pack, rel in zip(spec.packs, spec.pack_scales, strict=True):
component = _component_outside(
family,
mean=pack.mean,
scale=spec.scale * rel,
half_width=half_width,
)
total = total + component * Interval.point(pack.weight)
return totalOther public import paths
omnibias.core.tail_boundomnibias.core.mollifier.tail_bound
true_outside_mass
omnibias.core.mollifier.true_outside_massSource ↗true_outside_mass(spec: MollifierSpec, *, half_width: float) -> floatClosed-form signed outside mass (float64 evaluation of the same CDFs).
Used as the truth oracle for G3. Not a replacement for tail_bound.
Parameters
| Name | Type & default | Contract |
|---|---|---|
specpositional-or-keyword | MollifierSpecRequired | See the operation contract and implementation below. |
half_widthkeyword-only | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · tail bound sound grid and sample
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_tail_bound_sound_grid_and_sample() -> None:
"""G3: Interval contains the true outside mass; zero undercovers."""
rng = random.Random(0)
specs = [
design_order("tanh", 2, scale=0.25),
design_order("sigmoid", 2, scale=0.5),
design_order("gaussian", 2, scale=0.4),
design_order("tanh", 4, scale=0.3),
]
widths = [0.5, 1.0, 1.5, 2.0, 3.0] + [rng.uniform(0.4, 4.0) for _ in range(20)]
violations = 0
n = 0
for spec in specs:
for w in widths:
enclosed = tail_bound(spec, half_width=w)
truth = true_outside_mass(spec, half_width=w)
n += 1
if not enclosed.contains(truth):
violations += 1
assert n >= 100
assert violations == 0python -m pytest "packages/omnibias-core/tests/test_mollifier.py::test_tail_bound_sound_grid_and_sample" -qRead the implementation
def true_outside_mass(spec: MollifierSpec, *, half_width: float) -> float:
"""Closed-form signed outside mass (float64 evaluation of the same CDFs).
Used as the truth oracle for G3. Not a replacement for :func:`tail_bound`.
"""
from math import erf, exp, tanh
family = spec.family
w = float(half_width)
acc = 0.0
for pack, rel in zip(spec.packs, spec.pack_scales, strict=True):
s = spec.scale * rel
mu = pack.mean
left = (-w - mu) / s
right = (w - mu) / s
if family == "gaussian":
# Phi(x) = 0.5 (1 + erf(x / sqrt(2)))
inv = 0.7071067811865476 # 1/sqrt(2)
f_left = 0.5 * (1.0 + erf(left * inv))
f_right = 0.5 * (1.0 + erf(right * inv))
elif family == "logistic":
f_left = 1.0 / (1.0 + exp(-left))
f_right = 1.0 / (1.0 + exp(-right))
else:
f_left = 0.5 * (1.0 + tanh(left))
f_right = 0.5 * (1.0 + tanh(right))
acc += pack.weight * (f_left + (1.0 - f_right))
return acc