omnibias.core.scale
Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.
import omnibias.core.scaleModule contract & mathematical conventions
Scale flow and coarse-graining (theory 03-07).
The tempering scale alpha is a third axis: alpha_c -> inf is
neither collapse. The founding bias collapse is delta -> 0
(biases to sigma^(K-1)). Temperature collapse is beta -> inf
(feasibility). Do not conflate the two, and do not call scale flow
either of them.
The exact law sigma_alpha^(n)(u) = alpha^n sigma^(n)(alpha u) is
the tempered / make_tempered_fastpath combinator with
scale_power=0. Linear coarse-graining is exact; nonlinear flow
is a recorded truncation. Exponents are refused without that order.
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.
EffectiveOperator
omnibias.core.EffectiveOperatorSource ↗class EffectiveOperatorDataclass 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 |
|---|---|---|
slowdataclass field | tuple[ScaledPack, ...]Required | See the operation contract and implementation below. |
matrixdataclass field | tuple[tuple[float, ...], ...]Required | See the operation contract and implementation below. |
cutoffdataclass field | floatRequired | See the operation contract and implementation below. |
lineardataclass field | boolRequired | See the operation contract and implementation below. |
Executed regression · g3 linear exactness
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_g3_linear_exactness() -> None:
packs = (
ScaledPack(order=0, mean=-0.4, alpha=1.0),
ScaledPack(order=0, mean=0.4, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=8.0),
)
op = coarse_grain_linear(packs, cutoff=1.0, derivative_order=2)
assert len(op.slow) == 2
c = (0.3, -0.7)
xs = np.linspace(-10.0, 10.0, 30001)
dx = float(xs[1] - xs[0])
lu = np.zeros_like(xs)
for cj, q in zip(c, op.slow, strict=True):
lu = lu + cj * np.array(
[
q.weight
* (q.alpha ** (q.order + 2))
* eval_gaussian_derivative(q.alpha * (float(x) - q.mean), q.order + 2)
for x in xs
],
dtype=np.float64,
)
projected = []
for p in op.slow:
pv = np.array([p.value(float(x)) for x in xs], dtype=np.float64)
projected.append(float(np.dot(pv, lu) * dx))
got = op.apply(c)
for a, b in zip(got, projected, strict=True):
assert _rel_err(a, b) <= 1e-12python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -qFields & methods
slowfield
slow: tuple[ScaledPack, ...]Declared tuple[ScaledPack, ...] field on EffectiveOperator. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗matrixfield
matrix: tuple[tuple[float, ...], ...]Declared tuple[tuple[float, ...], ...] field on EffectiveOperator. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗cutofffield
cutoff: floatDeclared float field on EffectiveOperator. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗linearfield
linear: boolDeclared bool field on EffectiveOperator. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗applymethod
apply(self, coeffs: Sequence[float]) -> tuple[float, ...]See the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
coeffspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
Returns: tuple[float, ...]
Validation & failure cases
- When
len(coeffs) != len(self.slow), raisesValueError('coeff length must match the slow subspace').
Executed regression · g3 linear exactness
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_g3_linear_exactness() -> None:
packs = (
ScaledPack(order=0, mean=-0.4, alpha=1.0),
ScaledPack(order=0, mean=0.4, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=8.0),
)
op = coarse_grain_linear(packs, cutoff=1.0, derivative_order=2)
assert len(op.slow) == 2
c = (0.3, -0.7)
xs = np.linspace(-10.0, 10.0, 30001)
dx = float(xs[1] - xs[0])
lu = np.zeros_like(xs)
for cj, q in zip(c, op.slow, strict=True):
lu = lu + cj * np.array(
[
q.weight
* (q.alpha ** (q.order + 2))
* eval_gaussian_derivative(q.alpha * (float(x) - q.mean), q.order + 2)
for x in xs
],
dtype=np.float64,
)
projected = []
for p in op.slow:
pv = np.array([p.value(float(x)) for x in xs], dtype=np.float64)
projected.append(float(np.dot(pv, lu) * dx))
got = op.apply(c)
for a, b in zip(got, projected, strict=True):
assert _rel_err(a, b) <= 1e-12python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -qMethod implementation
def apply(self, coeffs: Sequence[float]) -> tuple[float, ...]:
if len(coeffs) != len(self.slow):
raise ValueError("coeff length must match the slow subspace")
out = []
for row in self.matrix:
out.append(sum(a * float(c) for a, c in zip(row, coeffs, strict=True)))
return tuple(out)Read the implementation
class EffectiveOperator:
slow: tuple[ScaledPack, ...]
matrix: tuple[tuple[float, ...], ...]
cutoff: float
linear: bool
def apply(self, coeffs: Sequence[float]) -> tuple[float, ...]:
if len(coeffs) != len(self.slow):
raise ValueError("coeff length must match the slow subspace")
out = []
for row in self.matrix:
out.append(sum(a * float(c) for a, c in zip(row, coeffs, strict=True)))
return tuple(out)Other public import paths
omnibias.core.EffectiveOperatoromnibias.core.scale.EffectiveOperator
FlowSystem
omnibias.core.FlowSystemSource ↗class FlowSystemDataclass 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.
Truncated beta function. truncation_order is required on every report.
Parameters
| Name | Type & default | Contract |
|---|---|---|
coefficientsdataclass field | Mapping[str, float]Required | See the operation contract and implementation below. |
truncation_orderdataclass field | intRequired | See the operation contract and implementation below. |
Executed regression · g6 exponent refuses without 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_g6_exponent_refuses_without_order() -> None:
packs = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=4.0),
)
system = flow_coefficients(packs, order=2)
fps = system.fixed_points()
exp = report_exponents(system, fps[0])
assert system.truncation_order == 2
assert len(exp) == 1
with pytest.raises(ValueError, match="truncation order"):
report_exponents(SimpleNamespace(coefficients=system.coefficients), fps[0])
with pytest.raises(ValueError, match="truncation"):
system.exponents(fps[0], truncation_order=0)
study = [FlowSystem(system.coefficients, truncation_order=o).exponents(fps[0])[0] for o in (1, 2, 3)]
assert len(study) == 3python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -qFields & methods
coefficientsfield
coefficients: Mapping[str, float]Declared Mapping[str, float] field on FlowSystem. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗truncation_orderfield
truncation_order: intDeclared int field on FlowSystem. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__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.truncation_order) < 1, raisesValueError('truncation_order must be >= 1 (nonlinear flow is truncated)').
Executed regression · g6 exponent refuses without 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_g6_exponent_refuses_without_order() -> None:
packs = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=4.0),
)
system = flow_coefficients(packs, order=2)
fps = system.fixed_points()
exp = report_exponents(system, fps[0])
assert system.truncation_order == 2
assert len(exp) == 1
with pytest.raises(ValueError, match="truncation order"):
report_exponents(SimpleNamespace(coefficients=system.coefficients), fps[0])
with pytest.raises(ValueError, match="truncation"):
system.exponents(fps[0], truncation_order=0)
study = [FlowSystem(system.coefficients, truncation_order=o).exponents(fps[0])[0] for o in (1, 2, 3)]
assert len(study) == 3python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -qMethod implementation
def __post_init__(self) -> None:
if int(self.truncation_order) < 1:
raise ValueError("truncation_order must be >= 1 (nonlinear flow is truncated)")
object.__setattr__(self, "coefficients", dict(self.coefficients))
object.__setattr__(self, "truncation_order", int(self.truncation_order))betamethod
beta(self, g: float) -> floatSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
gpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
Returns: float
Method implementation
def beta(self, g: float) -> float:
lin = float(self.coefficients.get("linear", 0.0))
quad = float(self.coefficients.get("quadratic", 0.0))
cub = float(self.coefficients.get("cubic", 0.0))
val = lin * g
if self.truncation_order >= 2:
val += quad * g * g
if self.truncation_order >= 3:
val += cub * g * g * g
return valfixed_pointsmethod
fixed_points(self) -> tuple[Mapping[str, float], ...]See the class contract above and the exact method implementation below.
Returns: tuple[Mapping[str, float], ...]
Executed regression · g6 exponent refuses without 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_g6_exponent_refuses_without_order() -> None:
packs = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=4.0),
)
system = flow_coefficients(packs, order=2)
fps = system.fixed_points()
exp = report_exponents(system, fps[0])
assert system.truncation_order == 2
assert len(exp) == 1
with pytest.raises(ValueError, match="truncation order"):
report_exponents(SimpleNamespace(coefficients=system.coefficients), fps[0])
with pytest.raises(ValueError, match="truncation"):
system.exponents(fps[0], truncation_order=0)
study = [FlowSystem(system.coefficients, truncation_order=o).exponents(fps[0])[0] for o in (1, 2, 3)]
assert len(study) == 3python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -qMethod implementation
def fixed_points(self) -> tuple[Mapping[str, float], ...]:
lin = float(self.coefficients.get("linear", 0.0))
quad = float(self.coefficients.get("quadratic", 0.0))
pts = [{"g": 0.0}]
if self.truncation_order >= 2 and abs(quad) > 0.0:
pts.append({"g": -lin / quad})
return tuple(pts)exponentsmethod
exponents(self, fp: Mapping[str, float], *, truncation_order: int | None=None) -> tuple[float, ...]Jacobian eigenvalues. Refuses if no truncation order is recorded.
Parameters
| Name | Type & default | Contract |
|---|---|---|
fppositional-or-keyword | Mapping[str, float]Required | See the operation contract and implementation below. |
truncation_orderkeyword-only | int | NoneDefault: None | See the operation contract and implementation below. |
Returns: tuple[float, ...]
Validation & failure cases
- When
order is None or int(order) < 1, raisesValueError('refuses to report an exponent without a truncation order').
Executed regression · g6 exponent refuses without 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_g6_exponent_refuses_without_order() -> None:
packs = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=4.0),
)
system = flow_coefficients(packs, order=2)
fps = system.fixed_points()
exp = report_exponents(system, fps[0])
assert system.truncation_order == 2
assert len(exp) == 1
with pytest.raises(ValueError, match="truncation order"):
report_exponents(SimpleNamespace(coefficients=system.coefficients), fps[0])
with pytest.raises(ValueError, match="truncation"):
system.exponents(fps[0], truncation_order=0)
study = [FlowSystem(system.coefficients, truncation_order=o).exponents(fps[0])[0] for o in (1, 2, 3)]
assert len(study) == 3python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -qMethod implementation
def exponents(self, fp: Mapping[str, float], *, truncation_order: int | None = None) -> tuple[float, ...]:
"""Jacobian eigenvalues. Refuses if no truncation order is recorded."""
order = self.truncation_order if truncation_order is None else truncation_order
if order is None or int(order) < 1:
raise ValueError("refuses to report an exponent without a truncation order")
g = float(fp["g"])
lin = float(self.coefficients.get("linear", 0.0))
quad = float(self.coefficients.get("quadratic", 0.0))
cub = float(self.coefficients.get("cubic", 0.0))
deriv = lin
if int(order) >= 2:
deriv += 2.0 * quad * g
if int(order) >= 3:
deriv += 3.0 * cub * g * g
return (float(deriv),)Read the implementation
class FlowSystem:
"""Truncated beta function. ``truncation_order`` is required on every report."""
coefficients: Mapping[str, float]
truncation_order: int
def __post_init__(self) -> None:
if int(self.truncation_order) < 1:
raise ValueError("truncation_order must be >= 1 (nonlinear flow is truncated)")
object.__setattr__(self, "coefficients", dict(self.coefficients))
object.__setattr__(self, "truncation_order", int(self.truncation_order))
def beta(self, g: float) -> float:
lin = float(self.coefficients.get("linear", 0.0))
quad = float(self.coefficients.get("quadratic", 0.0))
cub = float(self.coefficients.get("cubic", 0.0))
val = lin * g
if self.truncation_order >= 2:
val += quad * g * g
if self.truncation_order >= 3:
val += cub * g * g * g
return val
def fixed_points(self) -> tuple[Mapping[str, float], ...]:
lin = float(self.coefficients.get("linear", 0.0))
quad = float(self.coefficients.get("quadratic", 0.0))
pts = [{"g": 0.0}]
if self.truncation_order >= 2 and abs(quad) > 0.0:
pts.append({"g": -lin / quad})
return tuple(pts)
def exponents(self, fp: Mapping[str, float], *, truncation_order: int | None = None) -> tuple[float, ...]:
"""Jacobian eigenvalues. Refuses if no truncation order is recorded."""
order = self.truncation_order if truncation_order is None else truncation_order
if order is None or int(order) < 1:
raise ValueError("refuses to report an exponent without a truncation order")
g = float(fp["g"])
lin = float(self.coefficients.get("linear", 0.0))
quad = float(self.coefficients.get("quadratic", 0.0))
cub = float(self.coefficients.get("cubic", 0.0))
deriv = lin
if int(order) >= 2:
deriv += 2.0 * quad * g
if int(order) >= 3:
deriv += 3.0 * cub * g * g
return (float(deriv),)Other public import paths
omnibias.core.FlowSystemomnibias.core.scale.FlowSystem
ScaleBand
omnibias.core.ScaleBandSource ↗class ScaleBandDataclass 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 |
|---|---|---|
alpha_lodataclass field | floatRequired | See the operation contract and implementation below. |
alpha_hidataclass field | floatRequired | See the operation contract and implementation below. |
Executed regression · g5 vcycle reduces residual
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_vcycle_reduces_residual() -> None:
packs = (
ScaledPack(order=0, mean=-0.8, alpha=0.8),
ScaledPack(order=0, mean=0.8, alpha=0.8),
ScaledPack(order=0, mean=-0.4, alpha=2.0),
ScaledPack(order=0, mean=0.0, alpha=2.0),
ScaledPack(order=0, mean=0.4, alpha=2.0),
)
a = -stiffness_matrix(packs, derivative_order=2)
rng = np.random.default_rng(0)
true = rng.normal(size=len(packs))
rhs = a @ true
bands = (ScaleBand(0.5, 1.0), ScaleBand(1.5, 2.5))
u0 = np.zeros(len(packs))
single = _jacobi(a, rhs, u0.copy(), omega=0.6, sweeps=4)
cycled = np.asarray(
grid_free_vcycle(packs, rhs, bands=bands, u0=u0, pre_sweeps=2, post_sweeps=2),
dtype=np.float64,
)
r0 = float(np.linalg.norm(rhs))
r_single = residual_norm(packs, rhs, single)
r_cycle = residual_norm(packs, rhs, cycled)
assert r_cycle <= r0 / 5.0
assert r_cycle < r_singlepython -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -qFields & methods
alpha_lofield
alpha_lo: floatDeclared float field on ScaleBand. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗alpha_hifield
alpha_hi: floatDeclared float field on ScaleBand. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
not (lo > 0.0 and hi > lo), raisesValueError('ScaleBand needs 0 < alpha_lo < alpha_hi').
Executed regression · g5 vcycle reduces residual
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_vcycle_reduces_residual() -> None:
packs = (
ScaledPack(order=0, mean=-0.8, alpha=0.8),
ScaledPack(order=0, mean=0.8, alpha=0.8),
ScaledPack(order=0, mean=-0.4, alpha=2.0),
ScaledPack(order=0, mean=0.0, alpha=2.0),
ScaledPack(order=0, mean=0.4, alpha=2.0),
)
a = -stiffness_matrix(packs, derivative_order=2)
rng = np.random.default_rng(0)
true = rng.normal(size=len(packs))
rhs = a @ true
bands = (ScaleBand(0.5, 1.0), ScaleBand(1.5, 2.5))
u0 = np.zeros(len(packs))
single = _jacobi(a, rhs, u0.copy(), omega=0.6, sweeps=4)
cycled = np.asarray(
grid_free_vcycle(packs, rhs, bands=bands, u0=u0, pre_sweeps=2, post_sweeps=2),
dtype=np.float64,
)
r0 = float(np.linalg.norm(rhs))
r_single = residual_norm(packs, rhs, single)
r_cycle = residual_norm(packs, rhs, cycled)
assert r_cycle <= r0 / 5.0
assert r_cycle < r_singlepython -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -qMethod implementation
def __post_init__(self) -> None:
lo, hi = float(self.alpha_lo), float(self.alpha_hi)
if not (lo > 0.0 and hi > lo):
raise ValueError("ScaleBand needs 0 < alpha_lo < alpha_hi")
object.__setattr__(self, "alpha_lo", lo)
object.__setattr__(self, "alpha_hi", hi)containsmethod
contains(self, alpha: float) -> boolSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
alphapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
Returns: bool
Executed regression · g5 vcycle reduces residual
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_vcycle_reduces_residual() -> None:
packs = (
ScaledPack(order=0, mean=-0.8, alpha=0.8),
ScaledPack(order=0, mean=0.8, alpha=0.8),
ScaledPack(order=0, mean=-0.4, alpha=2.0),
ScaledPack(order=0, mean=0.0, alpha=2.0),
ScaledPack(order=0, mean=0.4, alpha=2.0),
)
a = -stiffness_matrix(packs, derivative_order=2)
rng = np.random.default_rng(0)
true = rng.normal(size=len(packs))
rhs = a @ true
bands = (ScaleBand(0.5, 1.0), ScaleBand(1.5, 2.5))
u0 = np.zeros(len(packs))
single = _jacobi(a, rhs, u0.copy(), omega=0.6, sweeps=4)
cycled = np.asarray(
grid_free_vcycle(packs, rhs, bands=bands, u0=u0, pre_sweeps=2, post_sweeps=2),
dtype=np.float64,
)
r0 = float(np.linalg.norm(rhs))
r_single = residual_norm(packs, rhs, single)
r_cycle = residual_norm(packs, rhs, cycled)
assert r_cycle <= r0 / 5.0
assert r_cycle < r_singlepython -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -qMethod implementation
def contains(self, alpha: float) -> bool:
return self.alpha_lo <= float(alpha) <= self.alpha_hiRead the implementation
class ScaleBand:
alpha_lo: float
alpha_hi: float
def __post_init__(self) -> None:
lo, hi = float(self.alpha_lo), float(self.alpha_hi)
if not (lo > 0.0 and hi > lo):
raise ValueError("ScaleBand needs 0 < alpha_lo < alpha_hi")
object.__setattr__(self, "alpha_lo", lo)
object.__setattr__(self, "alpha_hi", hi)
def contains(self, alpha: float) -> bool:
return self.alpha_lo <= float(alpha) <= self.alpha_hiOther public import paths
omnibias.core.ScaleBandomnibias.core.scale.ScaleBandomnibias.fields.scale.ScaleBand
ScaledPack
omnibias.core.ScaledPackSource ↗class ScaledPackDataclass 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 pack with an explicit tempering scale. Not a collapse parameter.
Parameters
| Name | Type & default | Contract |
|---|---|---|
orderdataclass field | intRequired | See the operation contract and implementation below. |
meandataclass field | floatRequired | See the operation contract and implementation below. |
alphadataclass field | floatRequired | See the operation contract and implementation below. |
weightdataclass field | floatDefault: 1.0 | See the operation contract and implementation below. |
basedataclass field | strDefault: _GAUSS | See the operation contract and implementation below. |
Executed regression · g1 worked tanh example
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_g1_worked_tanh_example() -> None:
pack = ScaledPack(order=2, mean=0.0, alpha=1.0, base="tanh")
got = rescale_pack(pack, 2.0).value(0.2)
ref = 4.0 * eval_tanh_derivative(0.4, 2)
assert abs(got - ref) <= 4.0 * math.ulp(ref)python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g1_worked_tanh_example" -qRegression example · g1 exact rescaling
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_g1_exact_rescaling() -> None:
factors = (1.0 / 1024.0, 1.0 / 8.0, 8.0, 1024.0)
for n in range(11):
pack = ScaledPack(order=n, mean=0.0, alpha=1.0, base="tanh")
for f in factors:
back = rescale_pack(rescale_pack(pack, f), 1.0 / f)
assert back.alpha == pack.alpha
u = 0.2
got = rescale_pack(pack, f).value(u)
ref = (f**n) * pack.value(f * u)
assert abs(got - ref) <= 4.0 * math.ulp(ref if ref != 0.0 else 1.0)python -m pytest packages/omnibias-core/tests/test_scale.py -k test_g1_exact_rescaling -qFields & methods
orderfield
order: intDeclared int field on ScaledPack. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗meanfield
mean: floatDeclared float field on ScaledPack. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗alphafield
alpha: floatDeclared float field on ScaledPack. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
Regression example · g1 exact rescaling
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_g1_exact_rescaling() -> None:
factors = (1.0 / 1024.0, 1.0 / 8.0, 8.0, 1024.0)
for n in range(11):
pack = ScaledPack(order=n, mean=0.0, alpha=1.0, base="tanh")
for f in factors:
back = rescale_pack(rescale_pack(pack, f), 1.0 / f)
assert back.alpha == pack.alpha
u = 0.2
got = rescale_pack(pack, f).value(u)
ref = (f**n) * pack.value(f * u)
assert abs(got - ref) <= 4.0 * math.ulp(ref if ref != 0.0 else 1.0)python -m pytest packages/omnibias-core/tests/test_scale.py -k test_g1_exact_rescaling -qweightfield
weight: float = 1.0Declared float field on ScaledPack. Default expression: 1.0.
basefield
base: str = _GAUSSDeclared str field on ScaledPack. Default expression: _GAUSS.
__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.order) < 0, raisesValueError('order must be >= 0'). - When
not float(self.alpha) > 0.0 or self.alpha != self.alpha, raisesValueError('alpha must be finite and positive').
Executed regression · g1 worked tanh example
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_g1_worked_tanh_example() -> None:
pack = ScaledPack(order=2, mean=0.0, alpha=1.0, base="tanh")
got = rescale_pack(pack, 2.0).value(0.2)
ref = 4.0 * eval_tanh_derivative(0.4, 2)
assert abs(got - ref) <= 4.0 * math.ulp(ref)python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g1_worked_tanh_example" -qMethod implementation
def __post_init__(self) -> None:
if int(self.order) < 0:
raise ValueError("order must be >= 0")
if not (float(self.alpha) > 0.0) or self.alpha != self.alpha:
raise ValueError("alpha must be finite and positive")
object.__setattr__(self, "order", int(self.order))
object.__setattr__(self, "mean", float(self.mean))
object.__setattr__(self, "alpha", float(self.alpha))
object.__setattr__(self, "weight", float(self.weight))
object.__setattr__(self, "base", str(self.base))to_pack_specmethod
to_pack_spec(self) -> PackSpecSee the class contract above and the exact method implementation below.
Returns: PackSpec
Method implementation
def to_pack_spec(self) -> PackSpec:
return PackSpec(order=self.order, mean=self.mean, weight=self.weight)valuemethod
value(self, x: float) -> floatSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
xpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
Returns: float
Executed regression · g1 worked tanh example
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_g1_worked_tanh_example() -> None:
pack = ScaledPack(order=2, mean=0.0, alpha=1.0, base="tanh")
got = rescale_pack(pack, 2.0).value(0.2)
ref = 4.0 * eval_tanh_derivative(0.4, 2)
assert abs(got - ref) <= 4.0 * math.ulp(ref)python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g1_worked_tanh_example" -qMethod implementation
def value(self, x: float) -> float:
u = x - self.mean
return self.weight * _tempered_eval(self.base, self.alpha, u, self.order)Read the implementation
class ScaledPack:
"""A pack with an explicit tempering scale. Not a collapse parameter."""
order: int
mean: float
alpha: float
weight: float = 1.0
base: str = _GAUSS
def __post_init__(self) -> None:
if int(self.order) < 0:
raise ValueError("order must be >= 0")
if not (float(self.alpha) > 0.0) or self.alpha != self.alpha:
raise ValueError("alpha must be finite and positive")
object.__setattr__(self, "order", int(self.order))
object.__setattr__(self, "mean", float(self.mean))
object.__setattr__(self, "alpha", float(self.alpha))
object.__setattr__(self, "weight", float(self.weight))
object.__setattr__(self, "base", str(self.base))
def to_pack_spec(self) -> PackSpec:
return PackSpec(order=self.order, mean=self.mean, weight=self.weight)
def value(self, x: float) -> float:
u = x - self.mean
return self.weight * _tempered_eval(self.base, self.alpha, u, self.order)Other public import paths
omnibias.core.ScaledPackomnibias.core.scale.ScaledPack
coarse_grain_linear
omnibias.core.coarse_grain_linearSource ↗coarse_grain_linear(packs: Sequence[ScaledPack], *, cutoff: float, derivative_order: int=2) -> EffectiveOperatorGalerkin restriction of a constant-coeff linear operator. Exact.
Parameters
| Name | Type & default | Contract |
|---|---|---|
packspositional-or-keyword | Sequence[ScaledPack]Required | See the operation contract and implementation below. |
cutoffkeyword-only | floatRequired | See the operation contract and implementation below. |
derivative_orderkeyword-only | intDefault: 2 | See the operation contract and implementation below. |
EffectiveOperatorExplicit validation & failure cases
- When
not slow, raisesValueError('cutoff leaves an empty slow subspace').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g3 linear exactness
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_g3_linear_exactness() -> None:
packs = (
ScaledPack(order=0, mean=-0.4, alpha=1.0),
ScaledPack(order=0, mean=0.4, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=8.0),
)
op = coarse_grain_linear(packs, cutoff=1.0, derivative_order=2)
assert len(op.slow) == 2
c = (0.3, -0.7)
xs = np.linspace(-10.0, 10.0, 30001)
dx = float(xs[1] - xs[0])
lu = np.zeros_like(xs)
for cj, q in zip(c, op.slow, strict=True):
lu = lu + cj * np.array(
[
q.weight
* (q.alpha ** (q.order + 2))
* eval_gaussian_derivative(q.alpha * (float(x) - q.mean), q.order + 2)
for x in xs
],
dtype=np.float64,
)
projected = []
for p in op.slow:
pv = np.array([p.value(float(x)) for x in xs], dtype=np.float64)
projected.append(float(np.dot(pv, lu) * dx))
got = op.apply(c)
for a, b in zip(got, projected, strict=True):
assert _rel_err(a, b) <= 1e-12python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -qRead the implementation
def coarse_grain_linear(
packs: Sequence[ScaledPack],
*,
cutoff: float,
derivative_order: int = 2,
) -> EffectiveOperator:
"""Galerkin restriction of a constant-coeff linear operator. Exact."""
slow = tuple(p for p in packs if p.alpha <= float(cutoff))
if not slow:
raise ValueError("cutoff leaves an empty slow subspace")
mat = []
for p in slow:
row = [overlap(p, q, derivative_order=int(derivative_order)) for q in slow]
mat.append(tuple(row))
return EffectiveOperator(slow=slow, matrix=tuple(mat), cutoff=float(cutoff), linear=True)Other public import paths
omnibias.core.coarse_grain_linearomnibias.core.scale.coarse_grain_linear
eval_gaussian_derivative
omnibias.core.eval_gaussian_derivativeSource ↗eval_gaussian_derivative(z: float, n: int) -> floatg^(n)(z) for g = exp(-z^2/2) via probabilists' Hermite.
Parameters
| Name | Type & default | Contract |
|---|---|---|
zpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
floatExecuted regression · g3 linear exactness
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_g3_linear_exactness() -> None:
packs = (
ScaledPack(order=0, mean=-0.4, alpha=1.0),
ScaledPack(order=0, mean=0.4, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=8.0),
)
op = coarse_grain_linear(packs, cutoff=1.0, derivative_order=2)
assert len(op.slow) == 2
c = (0.3, -0.7)
xs = np.linspace(-10.0, 10.0, 30001)
dx = float(xs[1] - xs[0])
lu = np.zeros_like(xs)
for cj, q in zip(c, op.slow, strict=True):
lu = lu + cj * np.array(
[
q.weight
* (q.alpha ** (q.order + 2))
* eval_gaussian_derivative(q.alpha * (float(x) - q.mean), q.order + 2)
for x in xs
],
dtype=np.float64,
)
projected = []
for p in op.slow:
pv = np.array([p.value(float(x)) for x in xs], dtype=np.float64)
projected.append(float(np.dot(pv, lu) * dx))
got = op.apply(c)
for a, b in zip(got, projected, strict=True):
assert _rel_err(a, b) <= 1e-12python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -qRegression example · g2 overlap matches quadrature
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_overlap_matches_quadrature() -> None:
cases = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=8.0),
ScaledPack(order=1, mean=0.0, alpha=1.0),
ScaledPack(order=1, mean=0.2, alpha=2.0),
ScaledPack(order=2, mean=-0.1, alpha=1.5),
)
for p in cases:
for q in cases:
for k in (0, 1, 2):
closed = overlap(p, q, derivative_order=k)
xs = np.linspace(-12.0, 12.0, 40001)
dx = float(xs[1] - xs[0])
qk = np.array(
[
q.weight
* (q.alpha ** (q.order + k))
* eval_gaussian_derivative(q.alpha * (float(x) - q.mean), q.order + k)
for x in xs
],
dtype=np.float64,
)
pv = np.array([p.value(float(x)) for x in xs], dtype=np.float64)
num = float(np.dot(pv, qk) * dx)
assert _rel_err(closed, num) <= 1e-12, (p, q, k, closed, num)python -m pytest packages/omnibias-core/tests/test_scale.py -k test_g2_overlap_matches_quadrature -qRead the implementation
def eval_gaussian_derivative(z: float, n: int) -> float:
"""``g^(n)(z)`` for ``g = exp(-z^2/2)`` via probabilists' Hermite."""
he = _horner(hermite_coeffs(int(n)), float(z))
return float(((-1) ** int(n)) * he * math.exp(-0.5 * float(z) * float(z)))Other public import paths
omnibias.core.eval_gaussian_derivativeomnibias.core.scale.eval_gaussian_derivative
flow_coefficients
omnibias.core.flow_coefficientsSource ↗flow_coefficients(dictionary: Sequence[ScaledPack], nonlinearity: str='quadratic', *, order: int) -> FlowSystemOne-loop polynomial beta from fast-mode overlaps. Truncation is recorded.
Parameters
| Name | Type & default | Contract |
|---|---|---|
dictionarypositional-or-keyword | Sequence[ScaledPack]Required | See the operation contract and implementation below. |
nonlinearitypositional-or-keyword | strDefault: 'quadratic' | See the operation contract and implementation below. |
orderkeyword-only | intRequired | See the operation contract and implementation below. |
FlowSystemExplicit validation & failure cases
- When
int(order) < 1, raisesValueError('order must be >= 1'). - When
nonlinearity != 'quadratic', raisesValueError("only nonlinearity='quadratic' is implemented").
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g6 exponent refuses without 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_g6_exponent_refuses_without_order() -> None:
packs = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=4.0),
)
system = flow_coefficients(packs, order=2)
fps = system.fixed_points()
exp = report_exponents(system, fps[0])
assert system.truncation_order == 2
assert len(exp) == 1
with pytest.raises(ValueError, match="truncation order"):
report_exponents(SimpleNamespace(coefficients=system.coefficients), fps[0])
with pytest.raises(ValueError, match="truncation"):
system.exponents(fps[0], truncation_order=0)
study = [FlowSystem(system.coefficients, truncation_order=o).exponents(fps[0])[0] for o in (1, 2, 3)]
assert len(study) == 3python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -qRead the implementation
def flow_coefficients(
dictionary: Sequence[ScaledPack],
nonlinearity: str = "quadratic",
*,
order: int,
) -> FlowSystem:
"""One-loop polynomial beta from fast-mode overlaps. Truncation is recorded."""
if int(order) < 1:
raise ValueError("order must be >= 1")
if nonlinearity != "quadratic":
raise ValueError("only nonlinearity='quadratic' is implemented")
fast = [p for p in dictionary if p.alpha == max(q.alpha for q in dictionary)]
slow = [p for p in dictionary if p.alpha == min(q.alpha for q in dictionary)]
loop = 0.0
if fast and slow:
loop = overlap(slow[0], fast[0], derivative_order=0)
return FlowSystem(
coefficients={"linear": 1.0, "quadratic": -abs(loop), "cubic": 0.1 * loop},
truncation_order=int(order),
)Other public import paths
omnibias.core.flow_coefficientsomnibias.core.scale.flow_coefficients
gram_matrix
omnibias.core.gram_matrixSource ↗gram_matrix(packs: Sequence[ScaledPack]) -> NDArray[np.float64]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 |
|---|---|---|
packspositional-or-keyword | Sequence[ScaledPack]Required | See the operation contract and implementation below. |
NDArray[np.float64]Read the implementation
def gram_matrix(packs: Sequence[ScaledPack]) -> NDArray[np.float64]:
n = len(packs)
g = np.zeros((n, n), dtype=np.float64)
for i, p in enumerate(packs):
for j, q in enumerate(packs):
g[i, j] = overlap(p, q, derivative_order=0)
return gOther public import paths
omnibias.core.gram_matrixomnibias.core.scale.gram_matrix
honesty_payload
omnibias.core.scale.honesty_payloadSource ↗honesty_payload() -> dict[str, object]The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.
dict[str, object]Executed regression · honesty third axis
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_honesty_third_axis() -> None:
payload = honesty_payload()
assert payload["third_axis"] is True
assert payload["founding_bias_collapse"] is False
assert payload["temperature_collapse"] is Falsepython -m pytest "packages/omnibias-core/tests/test_scale.py::test_honesty_third_axis" -qRead the implementation
def honesty_payload() -> dict[str, object]:
return {
"third_axis": True,
"founding_bias_collapse": False,
"temperature_collapse": False,
"linear_exact": True,
"nonlinear_truncated": True,
"exponent_requires_truncation_order": True,
}overlap
omnibias.core.overlapSource ↗overlap(p: ScaledPack, q: ScaledPack, *, derivative_order: int=0) -> floatInner product <p, d^k q / dx^k>. Gaussian is a finite exact GH rule.
Parameters
| Name | Type & default | Contract |
|---|---|---|
ppositional-or-keyword | ScaledPackRequired | See the operation contract and implementation below. |
qpositional-or-keyword | ScaledPackRequired | See the operation contract and implementation below. |
derivative_orderkeyword-only | intDefault: 0 | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
k < 0, raisesValueError('derivative_order must be >= 0'). - When
p.base != _GAUSS or q.base != _GAUSS, raisesValueError('closed-form overlap is implemented for gaussian packs').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g6 exponent refuses without 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_g6_exponent_refuses_without_order() -> None:
packs = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=4.0),
)
system = flow_coefficients(packs, order=2)
fps = system.fixed_points()
exp = report_exponents(system, fps[0])
assert system.truncation_order == 2
assert len(exp) == 1
with pytest.raises(ValueError, match="truncation order"):
report_exponents(SimpleNamespace(coefficients=system.coefficients), fps[0])
with pytest.raises(ValueError, match="truncation"):
system.exponents(fps[0], truncation_order=0)
study = [FlowSystem(system.coefficients, truncation_order=o).exponents(fps[0])[0] for o in (1, 2, 3)]
assert len(study) == 3python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -qRegression example · g2 overlap matches quadrature
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_overlap_matches_quadrature() -> None:
cases = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=8.0),
ScaledPack(order=1, mean=0.0, alpha=1.0),
ScaledPack(order=1, mean=0.2, alpha=2.0),
ScaledPack(order=2, mean=-0.1, alpha=1.5),
)
for p in cases:
for q in cases:
for k in (0, 1, 2):
closed = overlap(p, q, derivative_order=k)
xs = np.linspace(-12.0, 12.0, 40001)
dx = float(xs[1] - xs[0])
qk = np.array(
[
q.weight
* (q.alpha ** (q.order + k))
* eval_gaussian_derivative(q.alpha * (float(x) - q.mean), q.order + k)
for x in xs
],
dtype=np.float64,
)
pv = np.array([p.value(float(x)) for x in xs], dtype=np.float64)
num = float(np.dot(pv, qk) * dx)
assert _rel_err(closed, num) <= 1e-12, (p, q, k, closed, num)python -m pytest packages/omnibias-core/tests/test_scale.py -k test_g2_overlap_matches_quadrature -qRead the implementation
def overlap(p: ScaledPack, q: ScaledPack, *, derivative_order: int = 0) -> float:
"""Inner product ``<p, d^k q / dx^k>``. Gaussian is a finite exact GH rule."""
k = int(derivative_order)
if k < 0:
raise ValueError("derivative_order must be >= 0")
if p.base != _GAUSS or q.base != _GAUSS:
raise ValueError("closed-form overlap is implemented for gaussian packs")
wp, wq = p.weight, q.weight
ap, aq = p.alpha, q.alpha
np_, nq = p.order, q.order
pref = wp * wq * (ap**np_) * (aq ** (nq + k))
a2, b2 = ap * ap, aq * aq
gamma = a2 + b2
x0 = (a2 * p.mean + b2 * q.mean) / gamma
complete = math.exp(-a2 * b2 * (p.mean - q.mean) ** 2 / (2.0 * gamma))
deg = np_ + nq + k
hermegauss = cast(
Callable[[int], tuple[NDArray[np.float64], NDArray[np.float64]]],
np.polynomial.hermite_e.hermegauss,
)
nodes, weights = hermegauss(max(deg + 4, 8))
scale = math.sqrt(gamma)
acc = 0.0
for t, w in zip(nodes, weights, strict=True):
x = x0 + float(t) / scale
zp = ap * (x - p.mean)
zq = aq * (x - q.mean)
# strip the gaussians already in the completed-square measure
he_p = _horner(hermite_coeffs(np_), zp) * ((-1) ** np_)
he_q = _horner(hermite_coeffs(nq + k), zq) * ((-1) ** (nq + k))
acc += float(w) * he_p * he_q
return pref * complete * acc / scaleOther public import paths
omnibias.core.overlapomnibias.core.scale.overlap
report_exponents
omnibias.core.report_exponentsSource ↗report_exponents(system: object, fp: Mapping[str, float]) -> tuple[float, ...]Public reporter: refuses unless truncation_order is recorded.
Parameters
| Name | Type & default | Contract |
|---|---|---|
systempositional-or-keyword | objectRequired | See the operation contract and implementation below. |
fppositional-or-keyword | Mapping[str, float]Required | See the operation contract and implementation below. |
tuple[float, ...]Explicit validation & failure cases
- When
order is None, raisesValueError('refuses to report an exponent without a truncation order'). - When
not isinstance(system, FlowSystem), raisesTypeError('system must be a FlowSystem').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g6 exponent refuses without 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_g6_exponent_refuses_without_order() -> None:
packs = (
ScaledPack(order=0, mean=0.0, alpha=1.0),
ScaledPack(order=0, mean=0.0, alpha=4.0),
)
system = flow_coefficients(packs, order=2)
fps = system.fixed_points()
exp = report_exponents(system, fps[0])
assert system.truncation_order == 2
assert len(exp) == 1
with pytest.raises(ValueError, match="truncation order"):
report_exponents(SimpleNamespace(coefficients=system.coefficients), fps[0])
with pytest.raises(ValueError, match="truncation"):
system.exponents(fps[0], truncation_order=0)
study = [FlowSystem(system.coefficients, truncation_order=o).exponents(fps[0])[0] for o in (1, 2, 3)]
assert len(study) == 3python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -qRead the implementation
def report_exponents(system: object, fp: Mapping[str, float]) -> tuple[float, ...]:
"""Public reporter: refuses unless ``truncation_order`` is recorded."""
order = getattr(system, "truncation_order", None)
if order is None:
raise ValueError("refuses to report an exponent without a truncation order")
if not isinstance(system, FlowSystem):
raise TypeError("system must be a FlowSystem")
return system.exponents(fp)Other public import paths
omnibias.core.report_exponentsomnibias.core.scale.report_exponents
rescale_pack
omnibias.core.rescale_packSource ↗rescale_pack(pack: ScaledPack, factor: float) -> ScaledPackExact scale change: alpha -> factor * alpha. Bit-exact for dyadic factors.
Parameters
| Name | Type & default | Contract |
|---|---|---|
packpositional-or-keyword | ScaledPackRequired | See the operation contract and implementation below. |
factorpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
ScaledPackExplicit validation & failure cases
- When
not f > 0.0 or f != f, raisesValueError('factor must be finite and positive').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g1 worked tanh example
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_g1_worked_tanh_example() -> None:
pack = ScaledPack(order=2, mean=0.0, alpha=1.0, base="tanh")
got = rescale_pack(pack, 2.0).value(0.2)
ref = 4.0 * eval_tanh_derivative(0.4, 2)
assert abs(got - ref) <= 4.0 * math.ulp(ref)python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g1_worked_tanh_example" -qRegression example · g1 exact rescaling
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_g1_exact_rescaling() -> None:
factors = (1.0 / 1024.0, 1.0 / 8.0, 8.0, 1024.0)
for n in range(11):
pack = ScaledPack(order=n, mean=0.0, alpha=1.0, base="tanh")
for f in factors:
back = rescale_pack(rescale_pack(pack, f), 1.0 / f)
assert back.alpha == pack.alpha
u = 0.2
got = rescale_pack(pack, f).value(u)
ref = (f**n) * pack.value(f * u)
assert abs(got - ref) <= 4.0 * math.ulp(ref if ref != 0.0 else 1.0)python -m pytest packages/omnibias-core/tests/test_scale.py -k test_g1_exact_rescaling -qRead the implementation
def rescale_pack(pack: ScaledPack, factor: float) -> ScaledPack:
"""Exact scale change: ``alpha -> factor * alpha``. Bit-exact for dyadic factors."""
f = float(factor)
if not (f > 0.0) or f != f:
raise ValueError("factor must be finite and positive")
return ScaledPack(
order=pack.order,
mean=pack.mean,
alpha=pack.alpha * f,
weight=pack.weight,
base=pack.base,
)Other public import paths
omnibias.core.rescale_packomnibias.core.scale.rescale_pack
stiffness_matrix
omnibias.core.stiffness_matrixSource ↗stiffness_matrix(packs: Sequence[ScaledPack], *, derivative_order: int=2) -> NDArray[np.float64]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 |
|---|---|---|
packspositional-or-keyword | Sequence[ScaledPack]Required | See the operation contract and implementation below. |
derivative_orderkeyword-only | intDefault: 2 | See the operation contract and implementation below. |
NDArray[np.float64]Executed regression · g5 vcycle reduces residual
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_vcycle_reduces_residual() -> None:
packs = (
ScaledPack(order=0, mean=-0.8, alpha=0.8),
ScaledPack(order=0, mean=0.8, alpha=0.8),
ScaledPack(order=0, mean=-0.4, alpha=2.0),
ScaledPack(order=0, mean=0.0, alpha=2.0),
ScaledPack(order=0, mean=0.4, alpha=2.0),
)
a = -stiffness_matrix(packs, derivative_order=2)
rng = np.random.default_rng(0)
true = rng.normal(size=len(packs))
rhs = a @ true
bands = (ScaleBand(0.5, 1.0), ScaleBand(1.5, 2.5))
u0 = np.zeros(len(packs))
single = _jacobi(a, rhs, u0.copy(), omega=0.6, sweeps=4)
cycled = np.asarray(
grid_free_vcycle(packs, rhs, bands=bands, u0=u0, pre_sweeps=2, post_sweeps=2),
dtype=np.float64,
)
r0 = float(np.linalg.norm(rhs))
r_single = residual_norm(packs, rhs, single)
r_cycle = residual_norm(packs, rhs, cycled)
assert r_cycle <= r0 / 5.0
assert r_cycle < r_singlepython -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -qRead the implementation
def stiffness_matrix(packs: Sequence[ScaledPack], *, derivative_order: int = 2) -> NDArray[np.float64]:
n = len(packs)
a = np.zeros((n, n), dtype=np.float64)
for i, p in enumerate(packs):
for j, q in enumerate(packs):
a[i, j] = overlap(p, q, derivative_order=int(derivative_order))
return aOther public import paths
omnibias.core.stiffness_matrixomnibias.core.scale.stiffness_matrix