Skip to main content

omnibias.core.scale

0.5.0rc1Release candidatePython >=3.10Apache-2.0

Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.

import omnibias.core.scale
Module 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.

CLASS

EffectiveOperator​

omnibias.core.EffectiveOperatorSource ↗
class EffectiveOperator

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

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

Parameters

NameType & defaultContract
slowdataclass fieldtuple[ScaledPack, ...]RequiredSee the operation contract and implementation below.
matrixdataclass fieldtuple[tuple[float, ...], ...]RequiredSee the operation contract and implementation below.
cutoffdataclass fieldfloatRequiredSee the operation contract and implementation below.
lineardataclass fieldboolRequiredSee 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-12
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -q

Fields & 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: float

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

View source ↗
linearfield
linear: bool

Declared 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

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

Returns: tuple[float, ...]

Validation & failure cases
  • When len(coeffs) != len(self.slow), raises ValueError('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-12
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -q
Method 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)
View source ↗
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.EffectiveOperator
  • omnibias.core.scale.EffectiveOperator
CLASS

FlowSystem​

omnibias.core.FlowSystemSource ↗
class FlowSystem

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

Truncated beta function. truncation_order is required on every report.

Parameters

NameType & defaultContract
coefficientsdataclass fieldMapping[str, float]RequiredSee the operation contract and implementation below.
truncation_orderdataclass fieldintRequiredSee 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) == 3
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -q

Fields & 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: int

Declared 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) -> None

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

Returns: None

Validation & failure cases
  • When int(self.truncation_order) < 1, raises ValueError('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) == 3
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -q
Method 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))
View source ↗
betamethod
beta(self, g: float) -> float

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

Parameters

NameType & defaultContract
gpositional-or-keywordfloatRequiredSee 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 val
View source ↗
fixed_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) == 3
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -q
Method 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)
View source ↗
exponentsmethod
exponents(self, fp: Mapping[str, float], *, truncation_order: int | None=None) -> tuple[float, ...]

Jacobian eigenvalues. Refuses if no truncation order is recorded.

Parameters

NameType & defaultContract
fppositional-or-keywordMapping[str, float]RequiredSee the operation contract and implementation below.
truncation_orderkeyword-onlyint | NoneDefault: NoneSee the operation contract and implementation below.

Returns: tuple[float, ...]

Validation & failure cases
  • When order is None or int(order) < 1, raises ValueError('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) == 3
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -q
Method 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),)
View source ↗
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.FlowSystem
  • omnibias.core.scale.FlowSystem
CLASS

ScaleBand​

omnibias.core.ScaleBandSource ↗
class ScaleBand

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

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

Parameters

NameType & defaultContract
alpha_lodataclass fieldfloatRequiredSee the operation contract and implementation below.
alpha_hidataclass fieldfloatRequiredSee 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_single
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -q

Fields & methods

alpha_lofield
alpha_lo: float

Declared 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: float

Declared 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) -> None

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

Returns: None

Validation & failure cases
  • When not (lo > 0.0 and hi > lo), raises ValueError('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_single
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -q
Method 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)
View source ↗
containsmethod
contains(self, alpha: float) -> bool

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

Parameters

NameType & defaultContract
alphapositional-or-keywordfloatRequiredSee 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_single
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -q
Method implementation
    def contains(self, alpha: float) -> bool:
        return self.alpha_lo <= float(alpha) <= self.alpha_hi
View source ↗
Read 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_hi
Other public import paths
  • omnibias.core.ScaleBand
  • omnibias.core.scale.ScaleBand
  • omnibias.fields.scale.ScaleBand
CLASS

ScaledPack​

omnibias.core.ScaledPackSource ↗
class ScaledPack

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

A pack with an explicit tempering scale. Not a collapse parameter.

Parameters

NameType & defaultContract
orderdataclass fieldintRequiredSee the operation contract and implementation below.
meandataclass fieldfloatRequiredSee the operation contract and implementation below.
alphadataclass fieldfloatRequiredSee the operation contract and implementation below.
weightdataclass fieldfloatDefault: 1.0See the operation contract and implementation below.
basedataclass fieldstrDefault: _GAUSSSee 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" -q
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 -q

Fields & methods

orderfield
order: int

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

View source ↗
meanfield
mean: float

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

View source ↗
alphafield
alpha: float

Declared 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 -q
View source ↗
weightfield
weight: float = 1.0

Declared float field on ScaledPack. Default expression: 1.0.

View source ↗
basefield
base: str = _GAUSS

Declared str field on ScaledPack. Default expression: _GAUSS.

View source ↗
__post_init__method
__post_init__(self) -> None

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

Returns: None

Validation & failure cases
  • When int(self.order) < 0, raises ValueError('order must be >= 0').
  • When not float(self.alpha) > 0.0 or self.alpha != self.alpha, raises ValueError('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" -q
Method 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))
View source ↗
to_pack_specmethod
to_pack_spec(self) -> PackSpec

See 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)
View source ↗
valuemethod
value(self, x: float) -> float

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

Parameters

NameType & defaultContract
xpositional-or-keywordfloatRequiredSee 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" -q
Method implementation
    def value(self, x: float) -> float:
        u = x - self.mean
        return self.weight * _tempered_eval(self.base, self.alpha, u, self.order)
View source ↗
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.ScaledPack
  • omnibias.core.scale.ScaledPack
FUNCTION

coarse_grain_linear​

omnibias.core.coarse_grain_linearSource ↗
coarse_grain_linear(packs: Sequence[ScaledPack], *, cutoff: float, derivative_order: int=2) -> EffectiveOperator

Galerkin restriction of a constant-coeff linear operator. Exact.

Parameters

NameType & defaultContract
packspositional-or-keywordSequence[ScaledPack]RequiredSee the operation contract and implementation below.
cutoffkeyword-onlyfloatRequiredSee the operation contract and implementation below.
derivative_orderkeyword-onlyintDefault: 2See the operation contract and implementation below.
ReturnsEffectiveOperator
Explicit validation & failure cases
  • When not slow, raises ValueError('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-12
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -q
Read 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_linear
  • omnibias.core.scale.coarse_grain_linear
FUNCTION

eval_gaussian_derivative​

omnibias.core.eval_gaussian_derivativeSource ↗
eval_gaussian_derivative(z: float, n: int) -> float

g^(n)(z) for g = exp(-z^2/2) via probabilists' Hermite.

Parameters

NameType & defaultContract
zpositional-or-keywordfloatRequiredSee the operation contract and implementation below.
npositional-or-keywordintRequiredSee the operation contract and implementation below.
Returnsfloat
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-12
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g3_linear_exactness" -q
Regression 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 -q
Read 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_derivative
  • omnibias.core.scale.eval_gaussian_derivative
FUNCTION

flow_coefficients​

omnibias.core.flow_coefficientsSource ↗
flow_coefficients(dictionary: Sequence[ScaledPack], nonlinearity: str='quadratic', *, order: int) -> FlowSystem

One-loop polynomial beta from fast-mode overlaps. Truncation is recorded.

Parameters

NameType & defaultContract
dictionarypositional-or-keywordSequence[ScaledPack]RequiredSee the operation contract and implementation below.
nonlinearitypositional-or-keywordstrDefault: 'quadratic'See the operation contract and implementation below.
orderkeyword-onlyintRequiredSee the operation contract and implementation below.
ReturnsFlowSystem
Explicit validation & failure cases
  • When int(order) < 1, raises ValueError('order must be >= 1').
  • When nonlinearity != 'quadratic', raises ValueError("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) == 3
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -q
Read 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_coefficients
  • omnibias.core.scale.flow_coefficients
FUNCTION

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

NameType & defaultContract
packspositional-or-keywordSequence[ScaledPack]RequiredSee the operation contract and implementation below.
ReturnsNDArray[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 g
Other public import paths
  • omnibias.core.gram_matrix
  • omnibias.core.scale.gram_matrix
FUNCTION

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.

Returnsdict[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 False
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_honesty_third_axis" -q
Read 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,
    }
FUNCTION

overlap​

omnibias.core.overlapSource ↗
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.

Parameters

NameType & defaultContract
ppositional-or-keywordScaledPackRequiredSee the operation contract and implementation below.
qpositional-or-keywordScaledPackRequiredSee the operation contract and implementation below.
derivative_orderkeyword-onlyintDefault: 0See the operation contract and implementation below.
Returnsfloat
Explicit validation & failure cases
  • When k < 0, raises ValueError('derivative_order must be >= 0').
  • When p.base != _GAUSS or q.base != _GAUSS, raises ValueError('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) == 3
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -q
Regression 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 -q
Read 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 / scale
Other public import paths
  • omnibias.core.overlap
  • omnibias.core.scale.overlap
FUNCTION

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

NameType & defaultContract
systempositional-or-keywordobjectRequiredSee the operation contract and implementation below.
fppositional-or-keywordMapping[str, float]RequiredSee the operation contract and implementation below.
Returnstuple[float, ...]
Explicit validation & failure cases
  • When order is None, raises ValueError('refuses to report an exponent without a truncation order').
  • When not isinstance(system, FlowSystem), raises TypeError('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) == 3
python -m pytest "packages/omnibias-core/tests/test_scale.py::test_g6_exponent_refuses_without_order" -q
Read 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_exponents
  • omnibias.core.scale.report_exponents
FUNCTION

rescale_pack​

omnibias.core.rescale_packSource ↗
rescale_pack(pack: ScaledPack, factor: float) -> ScaledPack

Exact scale change: alpha -> factor * alpha. Bit-exact for dyadic factors.

Parameters

NameType & defaultContract
packpositional-or-keywordScaledPackRequiredSee the operation contract and implementation below.
factorpositional-or-keywordfloatRequiredSee the operation contract and implementation below.
ReturnsScaledPack
Explicit validation & failure cases
  • When not f > 0.0 or f != f, raises ValueError('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" -q
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 -q
Read 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_pack
  • omnibias.core.scale.rescale_pack
FUNCTION

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

NameType & defaultContract
packspositional-or-keywordSequence[ScaledPack]RequiredSee the operation contract and implementation below.
derivative_orderkeyword-onlyintDefault: 2See the operation contract and implementation below.
ReturnsNDArray[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_single
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -q
Read 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 a
Other public import paths
  • omnibias.core.stiffness_matrix
  • omnibias.core.scale.stiffness_matrix