Skip to main content

omnibias.core.realization.schema

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

Immutable descriptions of realizations and their observation scope.

The schema stores no tensors or backend imports. A finite observation vector does not determine a global function unless a separate determining argument is supplied. Parameter blocks have stable names and contiguous row-major slots.

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.

CONSTANT

IntegralKind​

omnibias.core.realization.IntegralKindSource ↗
IntegralKind = Literal['activation_window', 'domain_quadrature', 'measure']

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
IntegralKind = Literal["activation_window", "domain_quadrature", "measure"]
Other public import paths
  • omnibias.core.realization.IntegralKind
  • omnibias.core.realization.schema.IntegralKind
CLASS

LayerSpec​

omnibias.core.realization.LayerSpecSource ↗
class LayerSpec

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.

Affine layer followed by one of the six activation-level roles.

activation=None is a plain affine layer. Window parameters are the literal lower/upper shifts, or center/raw-width when window_parameterization is center_softplus_width. The latter matches the integral OperatorBlock.

Parameters

NameType & defaultContract
in_featuresdataclass fieldintRequiredSee the operation contract and implementation below.
out_featuresdataclass fieldintRequiredSee the operation contract and implementation below.
activationdataclass fieldstr | NoneDefault: 'tanh'See the operation contract and implementation below.
opdataclass fieldOperatorRoleDefault: 'identity'See the operation contract and implementation below.
derivative_orderdataclass fieldintDefault: 0See the operation contract and implementation below.
weight_namedataclass fieldstrDefault: ''See the operation contract and implementation below.
bias_namedataclass fieldstr | NoneDefault: NoneSee the operation contract and implementation below.
window_namesdataclass fieldtuple[str, str] | NoneDefault: NoneSee the operation contract and implementation below.
window_parameterizationdataclass fieldLiteral['endpoints', 'center_softplus_width']Default: 'endpoints'See the operation contract and implementation below.
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q

Fields & methods

in_featuresfield
in_features: int

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

View source ↗
out_featuresfield
out_features: int

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

View source ↗
activationfield
activation: str | None = 'tanh'

Declared str | None field on LayerSpec. Default expression: 'tanh'.

View source ↗
opfield
op: OperatorRole = 'identity'

Declared OperatorRole field on LayerSpec. Default expression: 'identity'.

View source ↗
derivative_orderfield
derivative_order: int = 0

Declared int field on LayerSpec. Default expression: 0.

View source ↗
weight_namefield
weight_name: str = ''

Declared str field on LayerSpec. Default expression: ''.

View source ↗
bias_namefield
bias_name: str | None = None

Declared str | None field on LayerSpec. Default expression: None.

View source ↗
window_namesfield
window_names: tuple[str, str] | None = None

Declared tuple[str, str] | None field on LayerSpec. Default expression: None.

View source ↗
window_parameterizationfield
window_parameterization: Literal['endpoints', 'center_softplus_width'] = 'endpoints'

Declared Literal['endpoints', 'center_softplus_width'] field on LayerSpec. Default expression: 'endpoints'.

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 min(self.in_features, self.out_features) < 1 or self.derivative_order < 0, raises ValueError('layer dimensions must be positive and derivative_order nonnegative').
  • When self.op not in {'identity', 'grad', 'laplacian', 'derivative', 'band', 'integral'}, raises ValueError(f'unknown operator role {self.op!r}').
  • When self.activation is None and self.op != 'identity', raises ValueError('operator roles require an activation').
  • When self.op in {'band', 'integral'} and self.window_names is None, raises ValueError('band/integral require two live window parameter blocks').
  • When len(self.window_names) != 2, raises ValueError('window_names must have two entries').
  • When self.window_parameterization not in {'endpoints', 'center_softplus_width'}, raises ValueError('unknown window parameterization').
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def __post_init__(self) -> None:
        if min(self.in_features, self.out_features) < 1 or self.derivative_order < 0:
            raise ValueError("layer dimensions must be positive and derivative_order nonnegative")
        if self.op not in {"identity", "grad", "laplacian", "derivative", "band", "integral"}:
            raise ValueError(f"unknown operator role {self.op!r}")
        if self.activation is None and self.op != "identity":
            raise ValueError("operator roles require an activation")
        if self.op in {"band", "integral"} and self.window_names is None:
            raise ValueError("band/integral require two live window parameter blocks")
        if self.window_names is not None:
            object.__setattr__(self, "window_names", tuple(self.window_names))
            if len(self.window_names) != 2:
                raise ValueError("window_names must have two entries")
        if self.window_parameterization not in {"endpoints", "center_softplus_width"}:
            raise ValueError("unknown window parameterization")
View source ↗
activation_orderproperty
activation_order(self) -> int

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

Returns: int

Method implementation
    def activation_order(self) -> int:
        return {"grad": 1, "laplacian": 2, "derivative": self.derivative_order}.get(self.op, 0)
View source ↗
Read the implementation
class LayerSpec:
    """Affine layer followed by one of the six activation-level roles.

    ``activation=None`` is a plain affine layer. Window parameters are the
    literal lower/upper shifts, or center/raw-width when ``window_parameterization``
    is ``center_softplus_width``. The latter matches the integral OperatorBlock.
    """

    in_features: int
    out_features: int
    activation: str | None = "tanh"
    op: OperatorRole = "identity"
    derivative_order: int = 0
    weight_name: str = ""
    bias_name: str | None = None
    window_names: tuple[str, str] | None = None
    window_parameterization: Literal["endpoints", "center_softplus_width"] = "endpoints"

    def __post_init__(self) -> None:
        if min(self.in_features, self.out_features) < 1 or self.derivative_order < 0:
            raise ValueError("layer dimensions must be positive and derivative_order nonnegative")
        if self.op not in {"identity", "grad", "laplacian", "derivative", "band", "integral"}:
            raise ValueError(f"unknown operator role {self.op!r}")
        if self.activation is None and self.op != "identity":
            raise ValueError("operator roles require an activation")
        if self.op in {"band", "integral"} and self.window_names is None:
            raise ValueError("band/integral require two live window parameter blocks")
        if self.window_names is not None:
            object.__setattr__(self, "window_names", tuple(self.window_names))
            if len(self.window_names) != 2:
                raise ValueError("window_names must have two entries")
        if self.window_parameterization not in {"endpoints", "center_softplus_width"}:
            raise ValueError("unknown window parameterization")

    @property
    def activation_order(self) -> int:
        return {"grad": 1, "laplacian": 2, "derivative": self.derivative_order}.get(self.op, 0)
Other public import paths
  • omnibias.core.realization.LayerSpec
  • omnibias.core.realization.schema.LayerSpec
CONSTANT

ObservationKind​

omnibias.core.realization.ObservationKindSource ↗
ObservationKind = Literal['values', 'coefficients', 'derivatives', 'residuals', 'integrals']

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
ObservationKind = Literal["values", "coefficients", "derivatives", "residuals", "integrals"]
Other public import paths
  • omnibias.core.realization.ObservationKind
  • omnibias.core.realization.schema.ObservationKind
CLASS

ObservationSpec​

omnibias.core.realization.ObservationSpecSource ↗
class ObservationSpec

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.

Scoped observations. Legacy integral observations mean domain quadrature.

Activation windows evaluate the actual integral-role realization at points. Domain and measure integrals use the declared weighted numerical rule; its provenance identifies the quadrature or sampled measure approximation.

Parameters

NameType & defaultContract
kinddataclass fieldObservationKindDefault: 'values'See the operation contract and implementation below.
scopedataclass fieldRealizationScopeDefault: 'finite_observations'See the operation contract and implementation below.
derivative_indicesdataclass fieldtuple[tuple[int, ...], ...]Default: ()See the operation contract and implementation below.
pointsdataclass fieldtuple[tuple[float, ...], ...]Default: ()See the operation contract and implementation below.
weightsdataclass fieldtuple[float, ...]Default: ()See the operation contract and implementation below.
domaindataclass fieldtuple[tuple[float, float], ...]Default: ()See the operation contract and implementation below.
labeldataclass fieldstrDefault: ''See the operation contract and implementation below.
provenancedataclass fieldstrDefault: ''See the operation contract and implementation below.
integral_kinddataclass fieldIntegralKind | NoneDefault: NoneSee the operation contract and implementation below.
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q

Fields & methods

kindfield
kind: ObservationKind = 'values'

Declared ObservationKind field on ObservationSpec. Default expression: 'values'.

View source ↗
scopefield
scope: RealizationScope = 'finite_observations'

Declared RealizationScope field on ObservationSpec. Default expression: 'finite_observations'.

Regression example · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest packages/omnibias-core/tests/test_realization_schema.py -k test_observation_scope_changes_identity_without_claiming_determination -q
View source ↗
derivative_indicesfield
derivative_indices: tuple[tuple[int, ...], ...] = ()

Declared tuple[tuple[int, ...], ...] field on ObservationSpec. Default expression: ().

View source ↗
pointsfield
points: tuple[tuple[float, ...], ...] = ()

Declared tuple[tuple[float, ...], ...] field on ObservationSpec. Default expression: ().

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

Declared tuple[float, ...] field on ObservationSpec. Default expression: ().

View source ↗
domainfield
domain: tuple[tuple[float, float], ...] = ()

Declared tuple[tuple[float, float], ...] field on ObservationSpec. Default expression: ().

View source ↗
labelfield
label: str = ''

Declared str field on ObservationSpec. Default expression: ''.

View source ↗
provenancefield
provenance: str = ''

Declared str field on ObservationSpec. Default expression: ''.

View source ↗
integral_kindfield
integral_kind: IntegralKind | None = None

Declared IntegralKind | None field on ObservationSpec. Default expression: None.

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 self.kind not in {'values', 'coefficients', 'derivatives', 'residuals', 'integrals'}, raises ValueError('unknown observation kind').
  • When self.scope not in {'finite_observations', 'polynomial_identity', 'declared_domain'}, raises ValueError('unknown observation scope').
  • When self.integral_kind not in {None, 'activation_window', 'domain_quadrature', 'measure'}, raises ValueError('unknown integral kind').
  • When self.integral_kind is not None and self.kind != 'integrals', raises ValueError('integral_kind is only valid for integral observations').
  • When any((i < 0 for index in self.derivative_indices for i in index)), raises ValueError('derivative multi-indices must be nonnegative').
  • When self.weights and len(self.weights) != len(self.points), raises ValueError('observation weights must match points').
  • When any((not math.isfinite(v) for row in self.points for v in row)), raises ValueError('observation points must be finite').
  • When any((not math.isfinite(v) for v in self.weights)), raises ValueError('observation weights must be finite').
  • When any((not (math.isfinite(lo) and math.isfinite(hi) and (lo <= hi)) for lo, hi in self.domain)), raises ValueError('domain must contain finite ordered bounds').
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def __post_init__(self) -> None:
        if self.kind not in {"values", "coefficients", "derivatives", "residuals", "integrals"}:
            raise ValueError("unknown observation kind")
        if self.scope not in {"finite_observations", "polynomial_identity", "declared_domain"}:
            raise ValueError("unknown observation scope")
        if self.integral_kind not in {None, "activation_window", "domain_quadrature", "measure"}:
            raise ValueError("unknown integral kind")
        if self.integral_kind is not None and self.kind != "integrals":
            raise ValueError("integral_kind is only valid for integral observations")
        for field in ("derivative_indices", "points", "domain"):
            value = getattr(self, field)
            object.__setattr__(self, field, tuple(tuple(row) for row in value))
        object.__setattr__(self, "weights", tuple(self.weights))
        if any(i < 0 for index in self.derivative_indices for i in index):
            raise ValueError("derivative multi-indices must be nonnegative")
        if self.weights and len(self.weights) != len(self.points):
            raise ValueError("observation weights must match points")
        if any(not math.isfinite(v) for row in self.points for v in row):
            raise ValueError("observation points must be finite")
        if any(not math.isfinite(v) for v in self.weights):
            raise ValueError("observation weights must be finite")
        if any(not (math.isfinite(lo) and math.isfinite(hi) and lo <= hi) for lo, hi in self.domain):
            raise ValueError("domain must contain finite ordered bounds")
View source ↗
Read the implementation
class ObservationSpec:
    """Scoped observations. Legacy integral observations mean domain quadrature.

    Activation windows evaluate the actual integral-role realization at points.
    Domain and measure integrals use the declared weighted numerical rule; its
    provenance identifies the quadrature or sampled measure approximation.
    """
    kind: ObservationKind = "values"
    scope: RealizationScope = "finite_observations"
    derivative_indices: tuple[tuple[int, ...], ...] = ()
    points: tuple[tuple[float, ...], ...] = ()
    weights: tuple[float, ...] = ()
    domain: tuple[tuple[float, float], ...] = ()
    label: str = ""
    provenance: str = ""
    integral_kind: IntegralKind | None = None

    def __post_init__(self) -> None:
        if self.kind not in {"values", "coefficients", "derivatives", "residuals", "integrals"}:
            raise ValueError("unknown observation kind")
        if self.scope not in {"finite_observations", "polynomial_identity", "declared_domain"}:
            raise ValueError("unknown observation scope")
        if self.integral_kind not in {None, "activation_window", "domain_quadrature", "measure"}:
            raise ValueError("unknown integral kind")
        if self.integral_kind is not None and self.kind != "integrals":
            raise ValueError("integral_kind is only valid for integral observations")
        for field in ("derivative_indices", "points", "domain"):
            value = getattr(self, field)
            object.__setattr__(self, field, tuple(tuple(row) for row in value))
        object.__setattr__(self, "weights", tuple(self.weights))
        if any(i < 0 for index in self.derivative_indices for i in index):
            raise ValueError("derivative multi-indices must be nonnegative")
        if self.weights and len(self.weights) != len(self.points):
            raise ValueError("observation weights must match points")
        if any(not math.isfinite(v) for row in self.points for v in row):
            raise ValueError("observation points must be finite")
        if any(not math.isfinite(v) for v in self.weights):
            raise ValueError("observation weights must be finite")
        if any(not (math.isfinite(lo) and math.isfinite(hi) and lo <= hi) for lo, hi in self.domain):
            raise ValueError("domain must contain finite ordered bounds")
Other public import paths
  • omnibias.core.realization.ObservationSpec
  • omnibias.core.realization.schema.ObservationSpec
CONSTANT

OperatorRole​

omnibias.core.realization.OperatorRoleSource ↗
OperatorRole = Literal['identity', 'grad', 'laplacian', 'derivative', 'band', 'integral']

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
OperatorRole = Literal["identity", "grad", "laplacian", "derivative", "band", "integral"]
Other public import paths
  • omnibias.core.realization.OperatorRole
  • omnibias.core.realization.schema.OperatorRole
CLASS

ParameterBlock​

omnibias.core.realization.ParameterBlockSource ↗
class ParameterBlock

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
namedataclass fieldstrRequiredSee the operation contract and implementation below.
shapedataclass fieldtuple[int, ...]RequiredSee the operation contract and implementation below.
offsetdataclass fieldintRequiredSee the operation contract and implementation below.
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Regression example · layout is stable and versioned

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_layout_is_stable_and_versioned() -> None:
    spec = RealizationSpec.dense((2, 3, 1))
    assert spec.layout.size == 13
    assert spec.layout.block("W1").shape == (1, 3)
    assert spec.layout.block_slice("b1") == slice(12, 13)
    assert spec.fingerprint() == RealizationSpec.dense([2, 3, 1]).fingerprint()
    assert spec.layout.fingerprint() != replace(spec.layout, version=2).fingerprint()
    with pytest.raises(ValueError, match="contiguous"):
        ParameterLayout((ParameterBlock("x", (2,), 1),))
    with pytest.raises(ValueError, match="unique"):
        ParameterLayout((ParameterBlock("x", (2,), 0), ParameterBlock("x", (1,), 2)))
python -m pytest packages/omnibias-core/tests/test_realization_schema.py -k test_layout_is_stable_and_versioned -q

Fields & methods

namefield
name: str

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

View source ↗
shapefield
shape: tuple[int, ...]

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

View source ↗
offsetfield
offset: int

Declared int field on ParameterBlock. 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 self.name or self.offset < 0 or any((d < 1 for d in self.shape)), raises ValueError('parameter blocks need a name, nonnegative offset and positive dimensions').
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def __post_init__(self) -> None:
        object.__setattr__(self, "shape", tuple(self.shape))
        if not self.name or self.offset < 0 or any(d < 1 for d in self.shape):
            raise ValueError("parameter blocks need a name, nonnegative offset and positive dimensions")
View source ↗
sizeproperty
size(self) -> int

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

Returns: int

Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def size(self) -> int:
        return math.prod(self.shape)
View source ↗
stopproperty
stop(self) -> int

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

Returns: int

Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def stop(self) -> int:
        return self.offset + self.size
View source ↗
sliceproperty
slice(self) -> slice

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

Returns: slice

Executed regression · layout is stable and versioned

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_layout_is_stable_and_versioned() -> None:
    spec = RealizationSpec.dense((2, 3, 1))
    assert spec.layout.size == 13
    assert spec.layout.block("W1").shape == (1, 3)
    assert spec.layout.block_slice("b1") == slice(12, 13)
    assert spec.fingerprint() == RealizationSpec.dense([2, 3, 1]).fingerprint()
    assert spec.layout.fingerprint() != replace(spec.layout, version=2).fingerprint()
    with pytest.raises(ValueError, match="contiguous"):
        ParameterLayout((ParameterBlock("x", (2,), 1),))
    with pytest.raises(ValueError, match="unique"):
        ParameterLayout((ParameterBlock("x", (2,), 0), ParameterBlock("x", (1,), 2)))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_layout_is_stable_and_versioned" -q
Method implementation
    def slice(self) -> slice:
        return slice(self.offset, self.stop)
View source ↗
Read the implementation
class ParameterBlock:
    name: str
    shape: tuple[int, ...]
    offset: int

    def __post_init__(self) -> None:
        object.__setattr__(self, "shape", tuple(self.shape))
        if not self.name or self.offset < 0 or any(d < 1 for d in self.shape):
            raise ValueError("parameter blocks need a name, nonnegative offset and positive dimensions")

    @property
    def size(self) -> int:
        return math.prod(self.shape)

    @property
    def stop(self) -> int:
        return self.offset + self.size

    @property
    def slice(self) -> slice:
        return slice(self.offset, self.stop)
Other public import paths
  • omnibias.core.realization.ParameterBlock
  • omnibias.core.realization.schema.ParameterBlock
CLASS

ParameterLayout​

omnibias.core.realization.ParameterLayoutSource ↗
class ParameterLayout

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
blocksdataclass fieldtuple[ParameterBlock, ...]RequiredSee the operation contract and implementation below.
versiondataclass fieldintDefault: 1See the operation contract and implementation below.
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Regression example · layout is stable and versioned

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_layout_is_stable_and_versioned() -> None:
    spec = RealizationSpec.dense((2, 3, 1))
    assert spec.layout.size == 13
    assert spec.layout.block("W1").shape == (1, 3)
    assert spec.layout.block_slice("b1") == slice(12, 13)
    assert spec.fingerprint() == RealizationSpec.dense([2, 3, 1]).fingerprint()
    assert spec.layout.fingerprint() != replace(spec.layout, version=2).fingerprint()
    with pytest.raises(ValueError, match="contiguous"):
        ParameterLayout((ParameterBlock("x", (2,), 1),))
    with pytest.raises(ValueError, match="unique"):
        ParameterLayout((ParameterBlock("x", (2,), 0), ParameterBlock("x", (1,), 2)))
python -m pytest packages/omnibias-core/tests/test_realization_schema.py -k test_layout_is_stable_and_versioned -q

Fields & methods

blocksfield
blocks: tuple[ParameterBlock, ...]

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

View source ↗
versionfield
version: int = 1

Declared int field on ParameterLayout. Default expression: 1.

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 self.version < 1, raises ValueError('layout version must be positive').
  • When block.name in names or block.offset != offset, raises ValueError('blocks must have unique names and contiguous offsets').
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def __post_init__(self) -> None:
        object.__setattr__(self, "blocks", tuple(self.blocks))
        if self.version < 1:
            raise ValueError("layout version must be positive")
        offset = 0
        names: set[str] = set()
        for block in self.blocks:
            if block.name in names or block.offset != offset:
                raise ValueError("blocks must have unique names and contiguous offsets")
            names.add(block.name)
            offset = block.stop
View source ↗
from_shapesmethod
from_shapes(cls, shapes: Mapping[str, Sequence[int]] | Sequence[tuple[str, Sequence[int]]], *, version: int=1) -> ParameterLayout

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

Parameters

NameType & defaultContract
shapespositional-or-keywordMapping[str, Sequence[int]] | Sequence[tuple[str, Sequence[int]]]RequiredSee the operation contract and implementation below.
versionkeyword-onlyintDefault: 1See the operation contract and implementation below.

Returns: ParameterLayout

Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def from_shapes(
        cls, shapes: Mapping[str, Sequence[int]] | Sequence[tuple[str, Sequence[int]]],
        *, version: int = 1,
    ) -> ParameterLayout:
        items = shapes.items() if isinstance(shapes, Mapping) else shapes
        blocks: list[ParameterBlock] = []
        offset = 0
        for name, shape in items:
            block = ParameterBlock(name, tuple(shape), offset)
            blocks.append(block)
            offset = block.stop
        return cls(tuple(blocks), version)
View source ↗
sizeproperty
size(self) -> int

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

Returns: int

Executed regression · layout is stable and versioned

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_layout_is_stable_and_versioned() -> None:
    spec = RealizationSpec.dense((2, 3, 1))
    assert spec.layout.size == 13
    assert spec.layout.block("W1").shape == (1, 3)
    assert spec.layout.block_slice("b1") == slice(12, 13)
    assert spec.fingerprint() == RealizationSpec.dense([2, 3, 1]).fingerprint()
    assert spec.layout.fingerprint() != replace(spec.layout, version=2).fingerprint()
    with pytest.raises(ValueError, match="contiguous"):
        ParameterLayout((ParameterBlock("x", (2,), 1),))
    with pytest.raises(ValueError, match="unique"):
        ParameterLayout((ParameterBlock("x", (2,), 0), ParameterBlock("x", (1,), 2)))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_layout_is_stable_and_versioned" -q
Method implementation
    def size(self) -> int:
        return self.blocks[-1].stop if self.blocks else 0
View source ↗
blockmethod
block(self, name: str) -> ParameterBlock

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

Parameters

NameType & defaultContract
namepositional-or-keywordstrRequiredSee the operation contract and implementation below.

Returns: ParameterBlock

Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def block(self, name: str) -> ParameterBlock:
        for block in self.blocks:
            if block.name == name:
                return block
        raise KeyError(f"unknown parameter block {name!r}")
View source ↗
block_slicemethod
block_slice(self, name: str) -> slice

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

Parameters

NameType & defaultContract
namepositional-or-keywordstrRequiredSee the operation contract and implementation below.

Returns: slice

Executed regression · layout is stable and versioned

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_layout_is_stable_and_versioned() -> None:
    spec = RealizationSpec.dense((2, 3, 1))
    assert spec.layout.size == 13
    assert spec.layout.block("W1").shape == (1, 3)
    assert spec.layout.block_slice("b1") == slice(12, 13)
    assert spec.fingerprint() == RealizationSpec.dense([2, 3, 1]).fingerprint()
    assert spec.layout.fingerprint() != replace(spec.layout, version=2).fingerprint()
    with pytest.raises(ValueError, match="contiguous"):
        ParameterLayout((ParameterBlock("x", (2,), 1),))
    with pytest.raises(ValueError, match="unique"):
        ParameterLayout((ParameterBlock("x", (2,), 0), ParameterBlock("x", (1,), 2)))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_layout_is_stable_and_versioned" -q
Method implementation
    def block_slice(self, name: str) -> slice:
        return self.block(name).slice
View source ↗
fingerprintmethod
fingerprint(self) -> str

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

Returns: str

Executed regression · layout is stable and versioned

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_layout_is_stable_and_versioned() -> None:
    spec = RealizationSpec.dense((2, 3, 1))
    assert spec.layout.size == 13
    assert spec.layout.block("W1").shape == (1, 3)
    assert spec.layout.block_slice("b1") == slice(12, 13)
    assert spec.fingerprint() == RealizationSpec.dense([2, 3, 1]).fingerprint()
    assert spec.layout.fingerprint() != replace(spec.layout, version=2).fingerprint()
    with pytest.raises(ValueError, match="contiguous"):
        ParameterLayout((ParameterBlock("x", (2,), 1),))
    with pytest.raises(ValueError, match="unique"):
        ParameterLayout((ParameterBlock("x", (2,), 0), ParameterBlock("x", (1,), 2)))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_layout_is_stable_and_versioned" -q
Method implementation
    def fingerprint(self) -> str:
        return _digest(asdict(self))
View source ↗
Read the implementation
class ParameterLayout:
    blocks: tuple[ParameterBlock, ...]
    version: int = 1

    def __post_init__(self) -> None:
        object.__setattr__(self, "blocks", tuple(self.blocks))
        if self.version < 1:
            raise ValueError("layout version must be positive")
        offset = 0
        names: set[str] = set()
        for block in self.blocks:
            if block.name in names or block.offset != offset:
                raise ValueError("blocks must have unique names and contiguous offsets")
            names.add(block.name)
            offset = block.stop

    @classmethod
    def from_shapes(
        cls, shapes: Mapping[str, Sequence[int]] | Sequence[tuple[str, Sequence[int]]],
        *, version: int = 1,
    ) -> ParameterLayout:
        items = shapes.items() if isinstance(shapes, Mapping) else shapes
        blocks: list[ParameterBlock] = []
        offset = 0
        for name, shape in items:
            block = ParameterBlock(name, tuple(shape), offset)
            blocks.append(block)
            offset = block.stop
        return cls(tuple(blocks), version)

    @property
    def size(self) -> int:
        return self.blocks[-1].stop if self.blocks else 0

    def block(self, name: str) -> ParameterBlock:
        for block in self.blocks:
            if block.name == name:
                return block
        raise KeyError(f"unknown parameter block {name!r}")

    def block_slice(self, name: str) -> slice:
        return self.block(name).slice

    def fingerprint(self) -> str:
        return _digest(asdict(self))
Other public import paths
  • omnibias.core.realization.ParameterLayout
  • omnibias.core.realization.schema.ParameterLayout
CONSTANT

RealizationScope​

omnibias.core.realization.RealizationScopeSource ↗
RealizationScope = Literal['finite_observations', 'polynomial_identity', 'declared_domain']

This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.

Read the implementation
RealizationScope = Literal["finite_observations", "polynomial_identity", "declared_domain"]
Other public import paths
  • omnibias.core.realization.RealizationScope
  • omnibias.core.realization.schema.RealizationScope
CLASS

RealizationSpec​

omnibias.core.realization.RealizationSpecSource ↗
class RealizationSpec

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
layersdataclass fieldtuple[LayerSpec, ...]RequiredSee the operation contract and implementation below.
layoutdataclass fieldParameterLayoutRequiredSee the operation contract and implementation below.
input_dimdataclass fieldintRequiredSee the operation contract and implementation below.
output_dimdataclass fieldintRequiredSee the operation contract and implementation below.
observationsdataclass fieldtuple[ObservationSpec, ...]Default: ()See the operation contract and implementation below.
namedataclass fieldstrDefault: 'realization'See the operation contract and implementation below.
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Regression example · layout is stable and versioned

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_layout_is_stable_and_versioned() -> None:
    spec = RealizationSpec.dense((2, 3, 1))
    assert spec.layout.size == 13
    assert spec.layout.block("W1").shape == (1, 3)
    assert spec.layout.block_slice("b1") == slice(12, 13)
    assert spec.fingerprint() == RealizationSpec.dense([2, 3, 1]).fingerprint()
    assert spec.layout.fingerprint() != replace(spec.layout, version=2).fingerprint()
    with pytest.raises(ValueError, match="contiguous"):
        ParameterLayout((ParameterBlock("x", (2,), 1),))
    with pytest.raises(ValueError, match="unique"):
        ParameterLayout((ParameterBlock("x", (2,), 0), ParameterBlock("x", (1,), 2)))
python -m pytest packages/omnibias-core/tests/test_realization_schema.py -k test_layout_is_stable_and_versioned -q

Fields & methods

layersfield
layers: tuple[LayerSpec, ...]

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

View source ↗
layoutfield
layout: ParameterLayout

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

View source ↗
input_dimfield
input_dim: int

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

View source ↗
output_dimfield
output_dim: int

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

View source ↗
observationsfield
observations: tuple[ObservationSpec, ...] = ()

Declared tuple[ObservationSpec, ...] field on RealizationSpec. Default expression: ().

View source ↗
namefield
name: str = 'realization'

Declared str field on RealizationSpec. Default expression: 'realization'.

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 self.layers or min(self.input_dim, self.output_dim) < 1, raises ValueError('a realization needs layers and positive dimensions').
  • When layer.in_features != width, raises ValueError('adjacent realization layer dimensions do not match').
  • When weight.shape != (layer.out_features, layer.in_features), raises ValueError('weight block shape does not match layer').
  • When self.layout.block(name).shape != (layer.out_features,), raises ValueError('bias/window block shape does not match layer').
  • When width != self.output_dim, raises ValueError('output_dim does not match final layer').
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def __post_init__(self) -> None:
        object.__setattr__(self, "layers", tuple(self.layers))
        object.__setattr__(self, "observations", tuple(self.observations))
        if not self.layers or min(self.input_dim, self.output_dim) < 1:
            raise ValueError("a realization needs layers and positive dimensions")
        width = self.input_dim
        for i, layer in enumerate(self.layers):
            if layer.in_features != width:
                raise ValueError("adjacent realization layer dimensions do not match")
            weight = self.layout.block(layer.weight_name or f"W{i}")
            if weight.shape != (layer.out_features, layer.in_features):
                raise ValueError("weight block shape does not match layer")
            for name in (() if layer.bias_name is None else (layer.bias_name,)) + (layer.window_names or ()):
                if self.layout.block(name).shape != (layer.out_features,):
                    raise ValueError("bias/window block shape does not match layer")
            width = layer.out_features
        if width != self.output_dim:
            raise ValueError("output_dim does not match final layer")
View source ↗
densemethod
dense(cls, widths: Sequence[int], *, activation: str='tanh', output_activation: str | None=None, bias: bool=True, name: str='dense') -> RealizationSpec

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

Parameters

NameType & defaultContract
widthspositional-or-keywordSequence[int]RequiredSee the operation contract and implementation below.
activationkeyword-onlystrDefault: 'tanh'See the operation contract and implementation below.
output_activationkeyword-onlystr | NoneDefault: NoneSee the operation contract and implementation below.
biaskeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
namekeyword-onlystrDefault: 'dense'See the operation contract and implementation below.

Returns: RealizationSpec

Validation & failure cases
  • When len(dims) < 2, raises ValueError('dense widths must contain input and output dimensions').
Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def dense(
        cls, widths: Sequence[int], *, activation: str = "tanh",
        output_activation: str | None = None, bias: bool = True, name: str = "dense",
    ) -> RealizationSpec:
        dims = tuple(widths)
        if len(dims) < 2:
            raise ValueError("dense widths must contain input and output dimensions")
        shapes: list[tuple[str, tuple[int, ...]]] = []
        layers: list[LayerSpec] = []
        for i, (din, dout) in enumerate(zip(dims[:-1], dims[1:], strict=True)):
            shapes.append((f"W{i}", (dout, din)))
            bname = f"b{i}" if bias else None
            if bname is not None:
                shapes.append((bname, (dout,)))
            act = output_activation if i == len(dims) - 2 else activation
            layers.append(LayerSpec(din, dout, act, weight_name=f"W{i}", bias_name=bname))
        return cls(tuple(layers), ParameterLayout.from_shapes(shapes), dims[0], dims[-1], name=name)
View source ↗
fingerprintmethod
fingerprint(self) -> str

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

Returns: str

Executed regression · observation scope changes identity without claiming determination

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_observation_scope_changes_identity_without_claiming_determination() -> None:
    sample = ObservationSpec(points=((0.0,),), label="one sample")
    assert sample.scope == "finite_observations"
    original = RealizationSpec.dense((1, 1))
    assert replace(original, observations=(sample,)).fingerprint() != original.fingerprint()
    with pytest.raises(ValueError, match="finite"):
        ObservationSpec(points=((float("inf"),),))
python -m pytest "packages/omnibias-core/tests/test_realization_schema.py::test_observation_scope_changes_identity_without_claiming_determination" -q
Method implementation
    def fingerprint(self) -> str:
        return _digest(asdict(self))
View source ↗
Read the implementation
class RealizationSpec:
    layers: tuple[LayerSpec, ...]
    layout: ParameterLayout
    input_dim: int
    output_dim: int
    observations: tuple[ObservationSpec, ...] = ()
    name: str = "realization"

    def __post_init__(self) -> None:
        object.__setattr__(self, "layers", tuple(self.layers))
        object.__setattr__(self, "observations", tuple(self.observations))
        if not self.layers or min(self.input_dim, self.output_dim) < 1:
            raise ValueError("a realization needs layers and positive dimensions")
        width = self.input_dim
        for i, layer in enumerate(self.layers):
            if layer.in_features != width:
                raise ValueError("adjacent realization layer dimensions do not match")
            weight = self.layout.block(layer.weight_name or f"W{i}")
            if weight.shape != (layer.out_features, layer.in_features):
                raise ValueError("weight block shape does not match layer")
            for name in (() if layer.bias_name is None else (layer.bias_name,)) + (layer.window_names or ()):
                if self.layout.block(name).shape != (layer.out_features,):
                    raise ValueError("bias/window block shape does not match layer")
            width = layer.out_features
        if width != self.output_dim:
            raise ValueError("output_dim does not match final layer")

    @classmethod
    def dense(
        cls, widths: Sequence[int], *, activation: str = "tanh",
        output_activation: str | None = None, bias: bool = True, name: str = "dense",
    ) -> RealizationSpec:
        dims = tuple(widths)
        if len(dims) < 2:
            raise ValueError("dense widths must contain input and output dimensions")
        shapes: list[tuple[str, tuple[int, ...]]] = []
        layers: list[LayerSpec] = []
        for i, (din, dout) in enumerate(zip(dims[:-1], dims[1:], strict=True)):
            shapes.append((f"W{i}", (dout, din)))
            bname = f"b{i}" if bias else None
            if bname is not None:
                shapes.append((bname, (dout,)))
            act = output_activation if i == len(dims) - 2 else activation
            layers.append(LayerSpec(din, dout, act, weight_name=f"W{i}", bias_name=bname))
        return cls(tuple(layers), ParameterLayout.from_shapes(shapes), dims[0], dims[-1], name=name)

    def fingerprint(self) -> str:
        return _digest(asdict(self))
Other public import paths
  • omnibias.core.realization.RealizationSpec
  • omnibias.core.realization.schema.RealizationSpec