Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Input and output specs

A spec states the kind and structure of a value without holding the value: a term spec declares one value, an input spec declares the inputs of a function or of a conditional distribution, and an output spec declares the outputs of a function or of a draw. A constraint declares the support of a numeric value. The values themselves are on Values and records.

Term specs

TermSpec

Bases: ABC

The kind and structure of one value, independent of its label.

Specs are immutable, hashable, and compare by declaration. Symbolic dimensions share a scope through nested schemas and declarations.

is_concrete property

Whether no symbolic dimensions remain.

free_dims property

The unbound symbolic dimension names this spec declares.

A spec that declares no shape and holds no schema has none, which is the default. A spec carrying a shape reports its symbolic entries; a spec carrying another schema reports that schema's, so a name is visible wherever it is declared and not only at the outermost level.

The names are what makes a template polymorphic. They live in one scope per template: the same name in two places is one dimension, whether the two places are sibling fields or one inside a term spec's own schema, and binding resolves every occurrence together.

with_dim_sizes(**sizes)

Return a new spec with symbolic dimensions replaced by the supplied sizes.

Parameters:

Name Type Description Default
**sizes int

Non-negative sizes keyed by dimension name. Unmentioned dimensions stay symbolic; names absent from the spec are ignored.

{}

Returns:

Type Description
Self

The substituted spec, with other metadata preserved.

Raises:

Type Description
TypeError

If a size is not an integer or is a bool.

ValueError

If a size is negative.

Source code in probpipe/core/_spec_base.py
def with_dim_sizes(self, **sizes: int) -> Self:
    """Return a new spec with symbolic dimensions replaced by the supplied sizes.

    Parameters
    ----------
    **sizes : int
        Non-negative sizes keyed by dimension name. Unmentioned dimensions
        stay symbolic; names absent from the spec are ignored.

    Returns
    -------
    Self
        The substituted spec, with other metadata preserved.

    Raises
    ------
    TypeError
        If a size is not an integer or is a ``bool``.
    ValueError
        If a size is negative.
    """
    return self._substitute_dims(_dim_sizes(sizes))

with_dim_names(**names)

Return a spec with symbolic dimensions renamed simultaneously.

Parameters:

Name Type Description Default
**names str

Old dimension names mapped to new names, each a Python identifier. Fixed sizes and unrelated metadata are preserved; unknown old names are ignored. Renaming two symbols to one joins their scopes.

{}

Returns:

Type Description
Self

The renamed spec. The original is unchanged.

Raises:

Type Description
TypeError

If a new name is not a string.

ValueError

If a new name is not a Python identifier.

Source code in probpipe/core/_spec_base.py
def with_dim_names(self, **names: str) -> Self:
    """Return a spec with symbolic dimensions renamed simultaneously.

    Parameters
    ----------
    **names : str
        Old dimension names mapped to new names, each a Python identifier.
        Fixed sizes and unrelated metadata are preserved; unknown old names
        are ignored. Renaming two symbols to one joins their scopes.

    Returns
    -------
    Self
        The renamed spec. The original is unchanged.

    Raises
    ------
    TypeError
        If a new name is not a string.
    ValueError
        If a new name is not a Python identifier.
    """
    return self._substitute_dims(_dim_renames(names))

bind_dims_from_value(value)

Unify against a value and return the resulting spec.

Parameters:

Name Type Description Default
value Any

The value supplying actual dimensions. All occurrences of a symbol must agree within this spec. Missing callable declarations leave their dimensions symbolic.

required

Returns:

Type Description
Self

A spec with the observed dimensions bound; no input is mutated.

Raises:

Type Description
ValueError

If kinds, structure, or repeated dimension sizes disagree.

Source code in probpipe/core/_spec_base.py
def bind_dims_from_value(self, value: Any) -> Self:
    """Unify against a value and return the resulting spec.

    Parameters
    ----------
    value : Any
        The value supplying actual dimensions. All occurrences of a symbol
        must agree within this spec. Missing callable declarations leave
        their dimensions symbolic.

    Returns
    -------
    Self
        A spec with the observed dimensions bound; no input is mutated.

    Raises
    ------
    ValueError
        If kinds, structure, or repeated dimension sizes disagree.
    """
    bindings: dict[str, int] = {}
    self._bind_dims_from_value(value, bindings, "value")
    return self._substitute_dims(bindings)

bind_dims_from_spec(other)

Unify against another declaration and return the resulting spec.

Parameters:

Name Type Description Default
other TermSpec

The spec to unify with, in one scope: a symbolic dimension on either side binds to the size the other side gives at its axis, and a name both sides declare is one dimension, which may stay free.

required

Returns:

Type Description
Self

This declaration with sizes learned from the other spec.

Raises:

Type Description
TypeError

If the argument is not a spec.

ValueError

If kinds, structure, or repeated sizes disagree, or two different symbolic dimensions meet at one axis, which with_dim_names resolves.

Source code in probpipe/core/_spec_base.py
def bind_dims_from_spec(self, other: TermSpec) -> Self:
    """Unify against another declaration and return the resulting spec.

    Parameters
    ----------
    other : TermSpec
        The spec to unify with, in one scope: a symbolic dimension on either
        side binds to the size the other side gives at its axis, and a name
        both sides declare is one dimension, which may stay free.

    Returns
    -------
    Self
        This declaration with sizes learned from the other spec.

    Raises
    ------
    TypeError
        If the argument is not a spec.
    ValueError
        If kinds, structure, or repeated sizes disagree, or two different
        symbolic dimensions meet at one axis, which ``with_dim_names`` resolves.
    """
    if not isinstance(other, TermSpec):
        raise TypeError(f"bind_dims_from_spec() expects a TermSpec, got {type(other).__name__}")
    bindings: dict[str, int] = {}
    _unify_specs(self, other, bindings, "other")
    return self._substitute_dims(bindings)

is_valid(value) abstractmethod

Whether value is a valid value for this spec.

Each concrete spec checks everything it declares; see its own is_valid docstring for the exact conditions.

Parameters:

Name Type Description Default
value Any

The concrete value to check against this spec.

required

Returns:

Type Description
bool

True iff value matches this spec; a value the spec does not describe returns False rather than raising. A spec swallows only the specific conditions that mean "does not match" (each spec documents its own); it does not suppress an unexpected error from inspecting a malformed value, so a genuine bug still surfaces.

Source code in probpipe/core/_spec_base.py
@abstractmethod
def is_valid(self, value: Any) -> bool:
    """Whether *value* is a valid value for this spec.

    Each concrete spec checks everything it declares; see its own
    ``is_valid`` docstring for the exact conditions.

    Parameters
    ----------
    value : Any
        The concrete value to check against this spec.

    Returns
    -------
    bool
        ``True`` iff *value* matches this spec; a value the spec does not
        describe returns ``False`` rather than raising. A spec swallows
        only the specific conditions that mean "does not match" (each spec
        documents its own); it does not suppress an unexpected error from
        inspecting a malformed value, so a genuine bug still surfaces.
    """

NumericSpec

Bases: TermSpec

A spec whose values have a flat numeric layout; this adds no kind.

Subclasses implement _vector_size for concrete specs. The public vector_size property rejects unbound dimensions before calling it.

vector_size property

The number of scalar coordinates in one value's flat numeric vector.

Raises:

Type Description
ValueError

If the spec still has symbolic dimensions. The message lists the dimensions that must first be made concrete.

NumericArraySpec(shape, dtype=None, support=None) dataclass

Bases: NumericSpec

A numeric-array value spec: an event shape plus optional metadata.

dtype and support are optional (default None); when unset the spec describes its shape only. Each dimension is either a fixed non-negative integer or a symbolic dimension name, which is a Python identifier such as n_obs. Repeated names must have the same size when a value is validated. dtype accepts any numpy.dtype spelling (a dtype instance, a scalar type such as jnp.float32, or a string such as "float32") and is normalised to numpy.dtype at construction, so equal dtypes compare and hash equal however they were spelled. A spec with dtype=None is not equal to one with a concrete dtype. support must be hashable when set.

Parameters:

Name Type Description Default
shape int, str, or sequence of int or str

The event shape, which holds one dimension per axis and is stored as a tuple. A single int or str is one dimension: 3 means (3,) and "n" means ("n",). A dimension that is an integer of another type, such as numpy.int64, is stored as a Python int.

required
dtype dtype - like

The dtype of the values. Stored as a numpy.dtype.

None
support Constraint

The constraint the entries of a value satisfy.

None

Raises:

Type Description
TypeError

If shape is not an int, a str, or an iterable of them, or a dimension is a bool or is neither an integer nor a string.

ValueError

If a dimension is a negative integer or a name that is not a Python identifier.

Source code in probpipe/core/_spec_base.py
def __init__(
    self,
    shape: ShapeLike,
    dtype: npt.DTypeLike | None = None,
    support: Constraint | None = None,
) -> None:
    dimensions = _as_shape(shape, what="NumericArraySpec shape")
    if support is not None:
        _require_hashable(support, context="NumericArraySpec.support")
    object.__setattr__(self, "shape", dimensions)
    object.__setattr__(self, "dtype", None if dtype is None else np.dtype(dtype))
    object.__setattr__(self, "support", support)

free_dims property

The symbolic entries of shape.

__repr__()

The shape, then the dtype and the support where they are set.

Source code in probpipe/core/_spec_base.py
def __repr__(self) -> str:
    """The shape, then the dtype and the support where they are set."""
    fields = [("shape", repr(self.shape))]
    if self.dtype is not None:
        fields.append(("dtype", format_dtype(self.dtype)))
    if self.support is not None:
        fields.append(("support", repr(self.support)))
    return term_repr(public_class_name(type(self)), None, fields)

is_valid(value)

Whether value is a numeric array (or scalar) matching this spec.

Checks that value is a numeric array-like (a numeric Python scalar, or an object with a numeric dtype and a shape) whose shape has the declared rank and fixed sizes (a numeric scalar has shape ()), with repeated symbolic dimensions agreeing, and whose dtype is same-kind castable to dtype when set — a widening promotion (e.g. float32 for a float64 spec) or a within-kind narrowing both pass, while a cross-kind conversion (e.g. a float where an integer dtype is declared) does not (a bare Python scalar reports the dtype np.asarray gives it). Strings, mappings, Python lists/tuples, and non-numeric arrays are invalid. Never raises on a mismatched value — a value the spec does not describe returns False.

support is not checked here. Unlike shape and dtype it is a data-dependent, element-wise check that cannot run under jax.jit tracing, and is_valid is the check Record construction runs (which happens inside traces). support is therefore descriptive metadata on the spec; is_valid validates structure only and so runs under jax.jit unchanged.

Source code in probpipe/core/_spec_base.py
def is_valid(self, value: Any) -> bool:
    """Whether *value* is a numeric array (or scalar) matching this spec.

    Checks that *value* is a numeric array-like (a numeric Python scalar,
    or an object with a numeric ``dtype`` and a ``shape``) whose shape
    has the declared rank and fixed sizes (a numeric scalar has shape
    ``()``), with repeated symbolic dimensions agreeing, and whose
    dtype is **same-kind castable** to ``dtype`` when set — a widening
    promotion (e.g. ``float32`` for a ``float64`` spec) or a within-kind
    narrowing both pass, while a cross-kind conversion (e.g. a float where
    an integer dtype is declared) does not (a bare Python scalar reports
    the dtype ``np.asarray`` gives it). Strings, mappings, Python
    lists/tuples, and non-numeric arrays are invalid. Never raises on a
    mismatched value — a value the spec does not describe returns
    ``False``.

    ``support`` is **not** checked here. Unlike shape and dtype it is a
    data-dependent, element-wise check that cannot run under ``jax.jit``
    tracing, and ``is_valid`` is the check ``Record`` construction runs
    (which happens inside traces). ``support`` is therefore descriptive
    metadata on the spec; :meth:`is_valid` validates structure only and so
    runs under ``jax.jit`` unchanged.
    """
    try:
        self._bind_dims_from_value(value, {}, "value")
    except ValueError:
        return False
    return True

OpaqueSpec(type=None, meta=None) dataclass

Bases: TermSpec

The fallback value spec, for a value no other spec describes.

An opaque value carries no exposed structure, as a string, a DataFrame, or an arbitrary Python object does.

Parameters:

Name Type Description Default
type type or None

The Python type of the values the spec admits, which is_valid checks. None admits every value that is not a mapping. Construction from a value infers it.

None
meta Hashable

Free-form metadata, such as units or a tag. It is part of the spec's equality and hash, and it is never checked against a value or inferred, so None unifies with a set meta, as an open type does with a set one.

None

Raises:

Type Description
TypeError

If type is neither a class nor None, or meta is not hashable.

is_valid(value)

Whether value is a valid opaque value: an instance of type, and no mapping.

A Mapping denotes tree structure, a subtree rather than a leaf, so no opaque spec admits one. With no type every other value is valid, including a numeric array or scalar, which a NumericArraySpec typically describes but an explicitly opaque field still accepts. meta is not checked against the value.

Notes

The record layer honours the same rule: mappings are never leaves, so Record construction materialises a mapping field value into a nested subtree.

Source code in probpipe/core/_spec_base.py
def is_valid(self, value: Any) -> bool:
    """Whether *value* is a valid opaque value: an instance of :attr:`type`, and no mapping.

    A ``Mapping`` denotes tree structure, a subtree rather than a leaf, so no
    opaque spec admits one. With no type every other value is valid,
    including a numeric array or scalar, which a :class:`NumericArraySpec`
    typically describes but an explicitly opaque field still accepts.
    ``meta`` is not checked against the value.

    Notes
    -----
    The record layer honours the same rule: mappings are never leaves, so
    :class:`~probpipe.Record` construction materialises a mapping field
    value into a nested subtree.
    """
    if isinstance(value, Mapping):
        return False
    return self.type is None or isinstance(_opaque_value(value), self.type)

__repr__()

The type and the metadata where they are set, so an open spec reads OpaqueSpec().

Source code in probpipe/core/_spec_base.py
def __repr__(self) -> str:
    """The type and the metadata where they are set, so an open spec reads ``OpaqueSpec()``."""
    return term_repr(public_class_name(type(self)), None, self._repr_arguments())

RecordSpec(_field_specs=None, /, **field_specs)

Bases: NamedTree[TermSpec], Immutable, TermSpec

Structural description of a value: its named, possibly-nested leaf structure.

A RecordSpec describes the structure of a value as a named tree — an insertion-ordered map of named fields whose only internal node is a nested RecordSpec and whose leaves are value specs. It is the schema of a Record (the value type with the same named-tree shape), not a description of an arbitrary JAX PyTree (see Terminology and JAX pytree contract below).

The word event follows probabilistic-programming usage and generalizes the event / event_shape notion from other PPLs (TensorFlow Probability, distrax, NumPyro). There, event_shape is the shape of a single draw of one array-valued random variable. ProbPipe supports distributions over general value types, not just arrays. The event in this context can thus be a structured Python object, with structure described by the RecordSpec.

Conformance and unification require the same field order at every record level. A raw mapping may list its keys in another order; function and kernel boundaries lay it out in declaration order before passing it to a body. An existing record in another order is refused with ValueError.

Terminology. Used precisely throughout this class:

  • field — one named object in the collection (here, a value spec), addressed by its /-delimited path from the root, such as "physics/mass", or a single name for a flat template. keys, values, items, iteration, and len range over the fields, keyed by path.
  • leaf — a terminal node: a TermSpec. A nested RecordSpec is a group, not a leaf; the fields are the leaves.
  • indexing — [] takes a path or a list of paths, as NamedTree states: one path gives the spec at that node, a value spec or a group's RecordSpec, and a list of paths gives the template cut down to those nodes, each at its own path. p in template holds for the path of a field or a group. The same paths index a template or the value it describes (template["physics"] / record["physics"]); this collection protocol is shared with Record.
  • canonical leaf order — the order in which leaves are traversed: depth-first, following each level's insertion order. This is the single ordering every leaf-wise operation uses. keys is its canonical definition — it returns the key (path) of every leaf in this order; the value-level to_vector and from_vector lay out and read leaves in it, and leaf_shapes is keyed by it.

JAX pytree contract. A RecordSpec is not a registered JAX pytree node — its value specs are atomic, so jax.tree_util.tree_leaves(template) == [template]. It is the schema of the value pytrees it describes, not a pytree itself (think of it as an enriched PyTreeDef that also carries each leaf's kind / shape).

For a value v it describes (a Record): a nested RecordSpec mirrors a nested Record (both internal nodes), and each value spec mirrors one field value. When every leaf is an array (the NumericRecordSpec / NumericRecord case), jax.tree_util.tree_leaves(v) returns the leaves in keys order. The one place the template's leaves and JAX's diverge is an OpaqueSpec leaf whose value is itself a JAX container (a tuple / list; a dict is never a leaf — mappings denote tree structure): the template counts it as a single leaf while JAX descends into it. See Record for the full statement.

Parameters:

Name Type Description Default
_field_specs Mapping or RecordSpec

The fields as a positional mapping, keyed by name or by /-joined path, or a RecordSpec whose fields are copied. Passing it together with keyword fields raises.

None
**field_specs tuple, TermSpec, or Mapping

Fields with non-empty names. Each value is one of:

  • tuple[int | str, ...] — fixed or symbolic shape of a numeric array leaf (e.g. () for a scalar, (3,) for a 3-vector, or ("obs", 3)); normalised to NumericArraySpec.
  • a TermSpec — an already-built spec (passed through).
  • RecordSpec — a nested sub-structure (an internal node).
  • a Mapping — a nested sub-structure whose values take these forms, built into a RecordSpec.
{}

Examples:

::

RecordSpec(x=(), y=(3,))                     # -> NumericRecordSpec
RecordSpec(label=OpaqueSpec(), x=())         # -> RecordSpec (mixed)
RecordSpec(physics=RecordSpec(force=(), mass=()), obs=())
Notes

Inspired by JAX's PyTreeDef: a template can reconstruct a value from its leaves and describes the expected structure for type-checking and vectorization. Leaves are stored as frozen, hashable spec objects, so a template is itself hashable (usable as a jit / treedef cache key). __getitem__ at a field's path returns the stored value spec, and at a group's path the group's RecordSpec (see Terminology); the enumeration of leaves is keys, and per-leaf array shapes (on a numeric template) live on leaf_shapes.

Symbolic array dimensions make a template polymorphic. free_dims returns their names and is_concrete is true only when all dimensions are fixed. Function invocation binds symbols in a call-local scope rather than mutating the declaration.

Calling RecordSpec(...) directly auto-promotes to a NumericRecordSpec when every spec is numeric (and every nested sub-template is itself all-numeric), so vector_size and leaf_shapes are reachable in the common all-numeric case without naming the subclass. Mixed templates (any opaque / None spec) stay plain RecordSpec and do not expose vector_size — it is not a meaningful quantity once opaque leaves are present. Empty subtrees in a numeric parent are normalized to NumericRecordSpec and contribute zero coordinates. A standalone RecordSpec() stays plain.

Source code in probpipe/core/_record_spec.py
def __init__(
    self,
    _field_specs: Mapping[str, _FieldSpecInput] | None = None,
    /,
    **field_specs: _FieldSpecInput,
):
    if _field_specs is not None:
        if field_specs:
            raise ValueError(
                f"pass {type(self).__name__} fields as a mapping or as keywords, not both"
            )
        nested = (
            dict(_field_specs.children)
            if isinstance(_field_specs, RecordSpec)
            else _unflatten_paths(_field_specs)
        )
    else:
        for name in field_specs:
            # Same rule as the positional path form enforces in
            # ``_unflatten_paths``; the keyword form reaches neither it
            # nor its message.
            if not name:
                raise ValueError("field key must be a non-empty string")
            _check_no_path_sep(name)
        nested = dict(field_specs)
    specs: dict[str, TermSpec] = {}
    for name, spec in nested.items():
        if isinstance(spec, RecordSpec):
            converted = spec
        elif isinstance(spec, Mapping):
            # A mapping spec is nested structure: materialise a subtree.
            converted = RecordSpec(spec)
        else:
            try:
                converted = _to_spec(spec)
            except TypeError as exc:
                raise TypeError(f"field {name!r}: {exc}") from None
            if not isinstance(converted, RecordSpec):
                self._check_leaf(name, converted)
        if (
            isinstance(self, NumericRecordSpec)
            and isinstance(converted, RecordSpec)
            and not isinstance(converted, NumericRecordSpec)
            and converted.is_numeric
        ):
            converted = NumericRecordSpec(converted)
        _require_hashable(converted, context=f"the spec of field {name!r}")
        specs[name] = converted
    self._post_validate(specs)
    object.__setattr__(self, "_tree", specs)

is_numeric property

Whether every reachable leaf implements NumericSpec.

Nested record schemas are checked recursively. Opaque, distribution, and callable leaves are non-numeric unless their spec implements the numeric mixin. The empty schema has no non-numeric leaves.

free_dims property

Symbolic dimension names declared anywhere in this template.

is_concrete property

Whether every dimension this template declares has a fixed size.

is_valid(value)

Whether a record or raw mapping satisfies the complete schema.

Fields must match exactly, including the order of an existing record. Raw mappings may list keys in any order. Nested structure, kinds, shapes and declared dtypes are checked, including agreement of repeated symbolic sizes. Structural mismatches return False; unexpected inspection errors propagate.

Source code in probpipe/core/_record_spec.py
def is_valid(self, value: Any) -> bool:
    """Whether a record or raw mapping satisfies the complete schema.

    Fields must match exactly, including the order of an existing record.
    Raw mappings may list keys in any order. Nested structure, kinds, shapes and declared
    dtypes are checked, including agreement of repeated symbolic sizes.
    Structural mismatches return False; unexpected inspection errors propagate.
    """
    from .record import Record

    if not isinstance(value, (Record, Mapping)):
        return False
    try:
        self._bind_dims_from_value(value, {}, "value")
    except (AttributeError, TypeError, ValueError):
        return False
    return True

numeric_subset()

Project to the NumericSpec-leaf sub-template.

Keeps every numeric leaf and drops non-numeric leaves and empty subtrees. Surviving leaves retain their metadata, canonical order and /-delimited paths.

The projection is idempotent. An all-numeric template without empty subtrees produces an equal NumericRecordSpec.

Returns:

Type Description
NumericRecordSpec

The numeric-leaf sub-template, so that vector_size and leaf_shapes are available.

Raises:

Type Description
ValueError

If no numeric leaves survive. The message names the dropped fields.

Source code in probpipe/core/_record_spec.py
def numeric_subset(self) -> NumericRecordSpec:
    """Project to the :class:`NumericSpec`-leaf sub-template.

    Keeps every numeric leaf and drops non-numeric leaves and empty
    subtrees. Surviving leaves retain their metadata, canonical order and
    ``/``-delimited paths.

    The projection is idempotent. An all-numeric template without empty
    subtrees produces an equal :class:`NumericRecordSpec`.

    Returns
    -------
    NumericRecordSpec
        The numeric-leaf sub-template, so that :attr:`vector_size` and
        :attr:`~NumericRecordSpec.leaf_shapes` are available.

    Raises
    ------
    ValueError
        If no numeric leaves survive. The message names the dropped fields.
    """
    specs = {path: spec for path, spec in self._walk_leaves() if isinstance(spec, NumericSpec)}
    if not specs:
        found = f"none of {list(self._tree)} is numeric" if self._tree else "it has no fields"
        raise ValueError(
            f"numeric_subset() found no numeric field in this {type(self).__name__}: {found}"
        )
    return NumericRecordSpec(specs)

infer_from(value) classmethod

Best-effort, lossy schema inferred by inspecting a value.

Two cases:

  • A Record already carries its authoritative schema, so infer_from returns its event_template unchanged.
  • A mapping of named fields (e.g. a Record's field dict) is inferred field by field: a nested Record field contributes its own schema; other tracked fields, distributions included, retain their specs. Callables become function specs; a numeric array or scalar becomes a NumericArraySpec of its shape, and a remaining raw value becomes the OpaqueSpec of its type. The result auto-promotes to a NumericRecordSpec when every field is numeric.

This is the fallback for wrapping a raw value that has no template yet (e.g. at a workflow boundary); for a value you already hold, read its authoritative event_template directly. Inference is lossy — it cannot recover an untracked array's declared dtype / support constraints or opaque metadata. A tracked field keeps its own spec. A Python list / tuple leaf (no .shape / .dtype) is treated as opaque even if it holds numbers; wrap it in np.asarray / jnp.asarray first for a numeric leaf.

Parameters:

Name Type Description Default
value Any

A Record, or a mapping of field name to value (arrays / scalars / nested Record\ s).

required

Returns:

Type Description
RecordSpec

The inferred schema (a NumericRecordSpec when every field is numeric).

Raises:

Type Description
TypeError

If value is neither a Record nor a mapping.

Source code in probpipe/core/_record_spec.py
@classmethod
def infer_from(cls, value: Any) -> RecordSpec:
    """Best-effort, **lossy** schema inferred by inspecting a value.

    Two cases:

    - A :class:`~probpipe.Record` already carries its authoritative schema,
      so ``infer_from`` returns its :attr:`~probpipe.Record.event_template`
      unchanged.
    - A **mapping** of named fields (e.g. a ``Record``'s field dict) is
      inferred field by field: a nested ``Record`` field contributes its
      own schema; other tracked fields, distributions included, retain
      their specs. Callables become function specs;
      a numeric array or scalar becomes a :class:`NumericArraySpec` of its
      shape, and a remaining raw value becomes the :class:`OpaqueSpec` of its
      type. The result auto-promotes to a :class:`NumericRecordSpec` when every
      field is numeric.

    This is the **fallback** for wrapping a raw value that has no template
    yet (e.g. at a workflow boundary); for a value you already hold, read
    its authoritative ``event_template`` directly. Inference is lossy — it
    cannot recover an untracked array's declared ``dtype`` / ``support``
    constraints or opaque metadata. A tracked field keeps its own spec.
    A Python ``list`` /
    ``tuple`` leaf (no ``.shape`` / ``.dtype``) is treated as opaque even if
    it holds numbers; wrap it in
    ``np.asarray`` / ``jnp.asarray`` first for a numeric leaf.

    Parameters
    ----------
    value : Any
        A :class:`~probpipe.Record`, or a mapping of field name to value
        (arrays / scalars / nested ``Record``\\ s).

    Returns
    -------
    RecordSpec
        The inferred schema (a :class:`NumericRecordSpec` when every
        field is numeric).

    Raises
    ------
    TypeError
        If *value* is neither a ``Record`` nor a mapping.
    """
    from .record import Record

    if isinstance(value, Record):
        return value.event_template
    if not isinstance(value, Mapping):
        raise TypeError(
            f"infer_from() expects a Record or a mapping of fields, got {type(value).__name__}"
        )

    def _leaf_spec(val: Any) -> _FieldSpecInput:
        from ..values._function_base import FunctionSpec
        from .tracked import TrackedTerm

        if isinstance(val, TrackedTerm):
            spec = getattr(val, "spec", None)
            if isinstance(spec, TermSpec):
                return spec
        if isinstance(val, Record):
            return val.event_template
        if callable(val):
            return FunctionSpec()
        # A mapping is never a leaf: it denotes tree structure, so infer a
        # nested template from it rather than an (invalid) opaque-leaf spec
        # — matching the constructor and the workflow-output wrap.
        if isinstance(val, Mapping):
            return cls.infer_from(val)
        # Any numeric array-like — bare arrays and native containers
        # (xarray / pandas / registered backends) alike — infers an
        # ``NumericArraySpec``; leaves are stored in native form, so nothing is
        # lost by classing them numeric.
        shape = _full_array_shape_or_none(val)
        return OpaqueSpec(type=type(val)) if shape is None else shape

    specs: dict[str, _FieldSpecInput] = {name: _leaf_spec(val) for name, val in value.items()}
    return RecordSpec(specs)

__repr__()

Each child by name, as the constructor takes it.

A bare array spec, which declares only a shape, renders as its shape-tuple shorthand, which the constructor accepts.

Source code in probpipe/core/_record_spec.py
def __repr__(self) -> str:
    """Each child by name, as the constructor takes it.

    A bare array spec, which declares only a shape, renders as its
    shape-tuple shorthand, which the constructor accepts.
    """
    fields = []
    for name, spec in self._tree.items():
        bare = (
            isinstance(spec, NumericArraySpec) and spec.dtype is None and spec.support is None
        )
        fields.append((name, repr(spec.shape) if bare else repr(spec)))
    return term_repr(type(self).__name__, None, fields)

NumericRecordSpec(_field_specs=None, /, **field_specs)

Bases: RecordSpec, NumericSpec

RecordSpec where every leaf is numeric.

Extends RecordSpec by requiring every leaf to implement NumericSpec. Shape tuples remain shorthand for array specs, and nested numeric records retain their structure. That restriction is what makes vector_size and leaf_shapes meaningful: vector_size is the length of the per-element 1-D vector — the total number of scalar elements across every numeric leaf — and from_vector takes a template of this class so that every field can be reconstructed from a slice of that vector. A batch of such values is a matrix of shape (*batch_shape, vector_size), not a single vector.

Use RecordSpec.infer_from on a NumericRecord (it auto-promotes) or call this constructor directly when you have the shape specs in hand.

Source code in probpipe/core/_record_spec.py
def __init__(
    self,
    _field_specs: Mapping[str, _FieldSpecInput] | None = None,
    /,
    **field_specs: _FieldSpecInput,
):
    super().__init__(_field_specs, **field_specs)
    size = None if self.free_dims else sum(spec.vector_size for spec in self._tree.values())
    object.__setattr__(self, "_cached_vector_size", size)

leaf_shapes property

Per-leaf array shapes, keyed by keys (canonical leaf order).

Array leaves retain their declared shape, including symbolic entries. Nested records contribute one entry per leaf. Other numeric kinds contribute their flat coordinate shape, (vector_size,); they must be concrete for that size to be available. General mixed schemas have no numeric layout and expose only their structural keys.

is_concrete property

Whether no symbolic dimension remains, as TermSpec defines it.

Read from the layout cached at construction, which is populated exactly when every dimension was concrete.

BatchSpec(element, levels=None, /, **level_shapes) dataclass

Bases: TermSpec

A term spec for a Batch: an element spec plus a named multiplicity.

BatchSpec(element, **levels) declares a batch whose elements are described by element, with one keyword per level mapping the level's name to the shape of its axes, outermost level first::

BatchSpec(NumericArraySpec(()), chain=4, draw=1000)
BatchSpec(NumericArraySpec(()), grid=(3, 4))       # one level of two axes
BatchSpec(NumericArraySpec(("n",)), draw="S")      # S draws, S unbound
BatchSpec(OpaqueSpec(), {"my level": 2})           # a name no keyword spells

Each level's shape is read as NumericArraySpec reads shape, so a single int or str is one axis: draw=4 is draw=(4,). A level name that cannot be written as a keyword argument, such as "my level" or "class", is given in a mapping passed positionally instead, and the two forms are not combined. levels returns the mapping, so BatchSpec(other_spec, batch.spec.levels) declares another element type over the same levels.

element_spec is the output spec of one element: its spec, element_spec.term_spec, and its outputs. A bare spec given as element takes the raw default: a single array or opaque value names the elements "element", as OutputSpec(element=NumericArraySpec(())), and a record, a distribution, a conditional distribution, or a batch of records or of distributions is in the positional form, as OutputSpec(RecordSpec(...)). For now a function's spec, and the spec of a batch of single arrays or opaque values, also name the elements "element", since the positional form does not take them yet. The repr leaves the raw default's name out.

The stored form is axis_groups and level_names: the batch axes tiled into named levels as Batch describes them. Level names are unique within a batch, and batch_shape / batch_size read off the tiling.

This is the single stored source of a batch's type, so it specifies the collection rather than one element, and Batch keeps no second copy of the multiplicity: its shape and level accessors read the stored spec.

Parameters:

Name Type Description Default
element OutputSpec or TermSpec

The output spec of one element, or the spec every element satisfies, including numeric-array and opaque kinds, which takes the raw default. Positional-only.

required
levels Mapping of str to shape

The levels as a mapping from level name to shape, outermost first. Positional-only, and given only when no level is given as a keyword.

None
**level_shapes int, str, or sequence of int or str

The levels as keywords, outermost first, each mapping a level name to the shape of its axes. A level name follows the rule for output names, so it is any non-empty string without /. Every level holds at least one axis, and each axis size is a non-negative integer or a symbolic dimension name, which is a Python identifier.

{}

Attributes:

Name Type Description
element_spec OutputSpec

The output spec of one element: its spec, element_spec.term_spec, and its outputs.

axis_groups tuple of tuple of int or str

The axis sizes each level holds, in order, outermost level first.

level_names tuple of str

One name per level, aligned with axis_groups.

batch_shape tuple of int or str

The batch axes, flat: the concatenation of axis_groups.

batch_size int

The total element count, prod(batch_shape).

Raises:

Type Description
TypeError

If element is neither a TermSpec nor an OutputSpec, or is an OutputSpec whose spec is not known yet; both a mapping and keywords are given; levels is not a mapping, or is given as a keyword holding a mapping; a key of the mapping is not a str; or a level's shape is not an int, a str, or a sequence of them.

ValueError

If no level is given, a level holds no axes, an axis size is negative or is a name that is not a Python identifier, or a level name is empty or contains /.

Notes

A batch whose elements name no kind is specified all the same: an opaque element spec is as well formed here as any other, which is what lets a batch of opaque values carry a term spec of its own.

An axis size may be a symbolic dimension name instead of an integer, as a NumericArraySpec shape entry may, so that a declaration can fix the number of levels while deferring how many elements each holds — "returns a batch of S draws" before S is known. The names share one scope with the element's schema, so a batch of ("n",) over arrays of shape ("n",) is square by declaration. Only the multiplicity must be concrete for a live Batch, which holds elements at positions; an element's own schema may stay polymorphic, since how many elements there are is a different question from what one of them looks like.

A duplicate level name cannot be written in either form, and Batch.with_level_names raises on a collision, since an operation that mints a level takes the name to give it.

Examples:

>>> from probpipe import NumericArraySpec, OutputSpec
>>> BatchSpec(NumericArraySpec(()), sample=4).element_spec
OutputSpec(element=NumericArraySpec(shape=()))
>>> BatchSpec(NumericArraySpec(()), sample=4)
BatchSpec(NumericArraySpec(shape=()), sample=4)
>>> BatchSpec(OutputSpec(x=NumericArraySpec(())), sample=4)
BatchSpec(OutputSpec(x=NumericArraySpec(shape=())), sample=4)
Source code in probpipe/core/_batch.py
def __init__(
    self,
    element: OutputSpec | TermSpec,
    levels: LevelsLike | None = None,
    /,
    **level_shapes: ShapeLike,
) -> None:
    if isinstance(level_shapes.get("levels"), Mapping) and levels is None:
        raise TypeError(
            "BatchSpec takes its levels mapping as the second positional argument, "
            "got levels= as a keyword"
        )
    names, groups = _as_levels(levels, level_shapes, what="BatchSpec")
    self._init_fields(element, groups, names)

levels property

The levels as a read-only mapping from level name to its axis sizes, outermost first.

BatchSpec(element, spec.levels) rebuilds a spec with the same levels, so another element type is declared over them.

batch_shape property

The batch axes, flat: the concatenation of axis_groups.

batch_size property

The total element count, prod(batch_shape).

Raises:

Type Description
ValueError

If the multiplicity is polymorphic. A count is a number, and a declaration that defers a size has none until it is bound — the same reason a polymorphic NumericRecordSpec has no flat layout.

free_dims property

The unbound dimensions of the element's schema and of the multiplicity.

One scope, as everywhere: a name shared between an axis size and the element's schema is one dimension, so a batch declared as ("n",) of arrays of shape ("n",) states that it is square.

free_axis_dims property

The unbound dimensions of the multiplicity alone.

What a live batch requires bound, since it holds elements at positions. An element's own schema may stay polymorphic: how many elements there are is a different question from what one of them looks like.

__replace__(**changes)

This spec with the given fields replaced, for copy.replace.

Parameters:

Name Type Description Default
**changes Any

New values of element_spec, axis_groups, or level_names. A new element_spec is read as the constructor reads element.

{}

Returns:

Type Description
BatchSpec

The rebuilt spec, checked as a constructed one is.

Raises:

Type Description
TypeError

If a change names any other field.

Source code in probpipe/core/_batch.py
def __replace__(self, **changes: Any) -> BatchSpec:
    """This spec with the given fields replaced, for ``copy.replace``.

    Parameters
    ----------
    **changes : Any
        New values of ``element_spec``, ``axis_groups``, or ``level_names``. A
        new ``element_spec`` is read as the constructor reads *element*.

    Returns
    -------
    BatchSpec
        The rebuilt spec, checked as a constructed one is.

    Raises
    ------
    TypeError
        If a change names any other field.
    """
    unknown = sorted(set(changes) - {"element_spec", "axis_groups", "level_names"})
    if unknown:
        raise TypeError(
            f"copy.replace() can change element_spec, axis_groups, and level_names of a "
            f"BatchSpec, got {', '.join(unknown)}"
        )
    if "element_spec" in changes:
        changes["element"] = changes.pop("element_spec")
    return self._replace(**changes)

__repr__()

The constructor call: the element, then one keyword per level.

The element shows as its bare spec when the element spec is the raw default for it, and as the element spec otherwise. A level of one axis shows its size alone, as draw=4, and a level name that no keyword spells puts the levels in one **{...} argument.

Source code in probpipe/core/_batch.py
def __repr__(self) -> str:
    """The constructor call: the element, then one keyword per level.

    The element shows as its bare spec when the element spec is the raw
    default for it, and as the element spec otherwise. A level of one axis
    shows its size alone, as ``draw=4``, and a level name that no keyword
    spells puts the levels in one ``**{...}`` argument.
    """
    return call_repr(
        "BatchSpec",
        [_element_repr(self.element_spec)],
        [
            (name, repr(group[0] if len(group) == 1 else group))
            for name, group in zip(self.level_names, self.axis_groups, strict=True)
        ],
    )

is_valid(value)

Whether value is a Batch whose own spec equals this one, element name aside.

The levels and the elements' specs are compared; the name an element spec gives single values is not. An opaque type this spec leaves open admits the type a batch inferred from its values, in the elements and in any record field of them. Anything that is not a Batch, or a Batch whose spec cannot be read, does not satisfy the spec and returns False. Mirrors is_valid.

Source code in probpipe/core/_batch.py
def is_valid(self, value: Any) -> bool:
    """Whether *value* is a :class:`Batch` whose own spec equals this one, element name aside.

    The levels and the elements' specs are compared; the name an element
    spec gives single values is not. An opaque type this spec leaves open
    admits the type a batch inferred from its values, in the elements and in
    any record field of them.
    Anything that is not a ``Batch``, or a ``Batch`` whose spec cannot be
    read, does not satisfy the spec and returns ``False``. Mirrors
    :meth:`~probpipe.RecordSpec.is_valid`.
    """
    if not isinstance(value, Batch):
        return False
    try:
        spec = value.spec
    except (AttributeError, TypeError):
        return False
    return _admits(self, spec)

FunctionSpec(input_spec=None, output_spec=None) dataclass

Bases: TermSpec

A callable's optional inputs and output spec.

Parameters:

Name Type Description Default
input_spec InputSpec or None

Named inputs. None leaves the input side unspecified.

None
output_spec OutputSpec or None

The returned term and its outputs. None leaves that side unspecified; an output spec that names its output but leaves its type unspecified, as OutputSpec(y=None), leaves only the returned term's kind open.

None

Raises:

Type Description
TypeError

If either side has the wrong spec type.

Notes

is_valid admits any callable without executing it. Dimension binding reads the input spec and output spec of each side when they are given, sharing one dimension scope across both sides. A side left unspecified adds no bindings. Incompatible input names, output names or forms, kinds, or dimensions raise ValueError. Labels are outside this spec; output names take part in matching the specs.

Examples:

A function's input spec and output spec bind a dimension that they share:

>>> from probpipe import FunctionSpec, InputSpec, NumericArraySpec, OutputSpec
>>> declared = FunctionSpec(
...     InputSpec(x=NumericArraySpec(("n",))),
...     OutputSpec(result=NumericArraySpec(("n",))),
... )
>>> actual = FunctionSpec(
...     InputSpec(x=NumericArraySpec((3,))),
...     OutputSpec(result=NumericArraySpec((3,))),
... )
>>> declared.bind_dims_from_spec(actual) == actual
True
>>> sorted(declared.free_dims)
['n']
Source code in probpipe/values/_function_base.py
def __init__(
    self, input_spec: InputSpec | None = None, output_spec: OutputSpec | None = None
) -> None:
    if input_spec is not None and not isinstance(input_spec, InputSpec):
        raise TypeError(
            f"FunctionSpec input_spec must be an InputSpec or None; got {type(input_spec).__name__}"
        )
    if output_spec is not None and not isinstance(output_spec, OutputSpec):
        raise TypeError(
            "FunctionSpec output_spec must be an OutputSpec or None; "
            f"got {type(output_spec).__name__}"
        )
    object.__setattr__(self, "input_spec", input_spec)
    object.__setattr__(self, "output_spec", output_spec)

free_dims property

Unbound dimensions across both sides, in one scope.

is_valid(value)

Whether value is callable; this does not execute or certify its body.

Source code in probpipe/values/_function_base.py
def is_valid(self, value: Any) -> bool:
    """Whether value is callable; this does not execute or certify its body."""
    return callable(value)

__repr__()

The declared sides, as the constructor takes them; an unspecified side is omitted.

Source code in probpipe/values/_function_base.py
def __repr__(self) -> str:
    """The declared sides, as the constructor takes them; an unspecified side is omitted."""
    fields = [
        (side, repr(declaration))
        for side, declaration in (
            ("input_spec", self.input_spec),
            ("output_spec", self.output_spec),
        )
        if declaration is not None
    ]
    return term_repr("FunctionSpec", None, fields)

DistributionSpec(event_spec) dataclass

Bases: TermSpec

The distribution kind's term spec: the output spec of one draw.

Parameters:

Name Type Description Default
event_spec OutputSpec or RecordSpec

The output spec of one draw. A bare RecordSpec completes to the positional form over it.

required

Raises:

Type Description
TypeError

If event_spec is neither, since a bare spec of another kind has no output name to complete it with.

ValueError

If event_spec leaves its type unspecified.

Notes

is_valid accepts a Distribution whose own event spec unifies with this one: the form and the output names agree, and then the outputs unify in one scope. An unset dtype accepts any dtype and a set one requires a same-kind cast, sizes agree with symbolic dimensions bound consistently, and support is not compared.

bind_dims_from_value binds a symbolic event spec from a law's own, and bind_dims_from_spec from another DistributionSpec, by that same rule. Repeated symbols share one scope, and conflicting sizes raise ValueError.

Examples:

>>> from probpipe import DistributionSpec, OutputSpec, NumericArraySpec
>>> declared = DistributionSpec(OutputSpec(x=NumericArraySpec(("n",))))
>>> bound = declared.bind_dims_from_spec(DistributionSpec(OutputSpec(x=NumericArraySpec((3,)))))
>>> bound.event_spec.term_spec.shape
(3,)
Source code in probpipe/distributions/_distribution.py
def __init__(self, event_spec: OutputSpec | RecordSpec) -> None:
    if isinstance(event_spec, RecordSpec):
        event_spec = OutputSpec(event_spec)
    elif not isinstance(event_spec, OutputSpec):
        raise TypeError(
            f"DistributionSpec.event_spec must be an OutputSpec or a RecordSpec; got "
            f"{type(event_spec).__name__}. Name the field, such as OutputSpec(x=...)"
        )
    if event_spec.term_spec is None:
        raise ValueError("DistributionSpec.event_spec does not declare a type")
    object.__setattr__(self, "event_spec", event_spec)

free_dims property

The unbound dimensions of the draw this declares.

__repr__()

The event spec, as the constructor takes it.

Source code in probpipe/distributions/_distribution.py
def __repr__(self) -> str:
    """The event spec, as the constructor takes it."""
    return term_repr("DistributionSpec", None, [("event_spec", repr(self.event_spec))])

is_valid(value)

Whether value is a Distribution whose event spec matches this one.

Source code in probpipe/distributions/_distribution.py
def is_valid(self, value: Any) -> bool:
    """Whether *value* is a ``Distribution`` whose event spec matches this one."""
    if not isinstance(value, Distribution):
        return False
    try:
        _unify_declarations(self.event_spec, value.event_spec, {}, "the event spec")
    except ValueError:
        return False
    return True

probpipe.distributions.ConditionalDistributionSpec(given_spec, event_spec) dataclass

Bases: TermSpec

The conditional kind's term spec: the inputs and the event spec.

Parameters:

Name Type Description Default
given_spec InputSpec, Mapping, RecordSpec, or OutputSpec

The named inputs a kernel conditions on, at least one.

required
event_spec OutputSpec or RecordSpec

The output spec of one produced draw, as for DistributionSpec. A bare RecordSpec completes to the positional form over it.

required

Raises:

Type Description
TypeError

If event_spec is neither an OutputSpec nor a RecordSpec, or given_spec is not a mapping of term specs.

ValueError

If given_spec has no inputs, the event spec leaves its type unspecified, or an input shares a name with an output.

Notes

is_valid accepts a ConditionalDistribution whose inputs have the same names and specs that unify with these, and whose event spec unifies with this one, both sides in one dimension scope.

Source code in probpipe/distributions/_conditional.py
def __init__(
    self,
    given_spec: InputSpec | Mapping[str, TermSpec | tuple] | RecordSpec | OutputSpec,
    event_spec: OutputSpec | RecordSpec,
) -> None:
    if isinstance(event_spec, RecordSpec):
        event_spec = OutputSpec(event_spec)
    elif not isinstance(event_spec, OutputSpec):
        raise TypeError(
            f"ConditionalDistributionSpec.event_spec must be an OutputSpec or a RecordSpec, "
            f"got {type(event_spec).__name__}"
        )
    if event_spec.term_spec is None:
        raise ValueError("ConditionalDistributionSpec.event_spec does not declare a type")
    given_spec = _complete_given_spec(given_spec)
    _check_disjoint_sides(given_spec, event_spec, "ConditionalDistributionSpec")
    object.__setattr__(self, "given_spec", given_spec)
    object.__setattr__(self, "event_spec", event_spec)

free_dims property

The unbound dimensions of both sides, which share one scope.

__repr__()

The inputs and the event spec, as the constructor takes them.

Source code in probpipe/distributions/_conditional.py
def __repr__(self) -> str:
    """The inputs and the event spec, as the constructor takes them."""
    return term_repr(
        "ConditionalDistributionSpec",
        None,
        [("given_spec", repr(self.given_spec)), ("event_spec", repr(self.event_spec))],
    )

is_valid(value)

Whether value is a ConditionalDistribution whose specs match these.

Source code in probpipe/distributions/_conditional.py
def is_valid(self, value: Any) -> bool:
    """Whether *value* is a ``ConditionalDistribution`` whose specs match these."""
    if not isinstance(value, ConditionalDistribution):
        return False
    try:
        self._unify_with(value.given_spec, value.event_spec, {}, "the specs")
    except ValueError:
        return False
    return True

Input and output specs

An InputSpec reads another input spec, a mapping, a RecordSpec's top-level fields, or an OutputSpec's outputs. Copying an input spec preserves its optional inputs. Tuple shapes are shorthand for NumericArraySpec, in input declarations and keyword output declarations alike:

from probpipe import InputSpec, OutputSpec, RecordSpec

inputs = InputSpec(mu=(), observations=(100,))
event = OutputSpec(RecordSpec(mu=(), sigma=()))
mu_input = InputSpec(event[["mu"]])

Pass a law's event_spec directly as given_spec when a kernel takes those outputs as inputs. Use event_spec[["mu"]] to retain one output, or event_spec.without("sigma") to remove an output. To pass a whole record as one input, retain its named group with list selection. These declarations name inputs; passing the law itself does not describe their types.

Input list selection retains declaration order and optional flags. Merging input specs with left & right retains the first type of a shared input after checking compatibility. A shared input is optional only when both sides mark it optional. A Python parameter's default marks its declared input optional; declaring an optional input for a parameter with no default is an error.

Record field order is part of a declaration. An existing record or record spec in another order does not conform, including inside a nested record. At function input and return boundaries, and when binding a kernel's conditioning values, a raw mapping may arrive in any order: the body and returned value receive its fields in declaration order. This leaves the caller's mapping unchanged. Raw mappings supplied as density values are arranged against the law's event spec before type inference, including nested records. Their insertion order does not constrain the event layout. A constructed Record already has an ordered declaration and must conform in that order.

InputSpec.without raises KeyError for a name it does not declare.

InputSpec(inputs=None, /, **inputs_by_name) dataclass

Bases: Mapping[str, TermSpec]

An immutable, flat mapping of input names to term specs.

An input is required or optional. A binding may omit an optional input, which then takes the default of the function or conditional distribution that owns it; with_optional marks inputs optional, and the optional inputs are part of the spec, so they take part in equality and hashing.

Parameters:

Name Type Description Default
inputs InputSpec, Mapping, RecordSpec, or OutputSpec

Inputs in their source's order. A record spec supplies one input per top-level field, an output spec one per output, and another InputSpec preserves its optional flags. Other sources supply required inputs.

None
**inputs_by_name TermSpec or tuple

Alternatively, the inputs by keyword, including RecordSpec-valued inputs. A tuple of sizes is converted to a NumericArraySpec of that shape. No constructor keyword is reserved.

{}

Raises:

Type Description
TypeError

If the source is unsupported, positional and keyword forms are combined, an output spec has an unspecified type, or an input's type is not a hashable TermSpec or a tuple of sizes. An input's type cannot be None.

ValueError

If an input name is not a non-keyword Python identifier, including path keys.

Source code in probpipe/core/_specs.py
def __init__(
    self,
    inputs: InputSpec | Mapping[str, TermSpec | tuple] | RecordSpec | OutputSpec | None = None,
    /,
    **inputs_by_name: TermSpec | tuple,
) -> None:
    optional = frozenset()
    if inputs is not None:
        if inputs_by_name:
            raise TypeError("pass InputSpec inputs as a mapping or as keywords, not both")
        if isinstance(inputs, InputSpec):
            optional = inputs.optional
            inputs = inputs._inputs
        elif isinstance(inputs, RecordSpec):
            inputs = inputs.children
        elif isinstance(inputs, OutputSpec):
            if inputs.term_spec is None:
                raise TypeError(
                    "cannot read inputs from an OutputSpec whose type is unspecified. "
                    "Declare its term_spec first"
                )
            inputs = inputs.outputs
        elif not isinstance(inputs, Mapping):
            raise TypeError(
                f"cannot read inputs from {type(inputs).__name__}. "
                "Pass an InputSpec, a mapping, a RecordSpec, or an OutputSpec"
            )
    else:
        inputs = inputs_by_name
    input_types = {
        name: _to_spec(spec) if isinstance(spec, tuple) else spec
        for name, spec in inputs.items()
    }
    for name, spec in input_types.items():
        _check_input(name, spec)
    object.__setattr__(self, "_inputs", input_types)
    object.__setattr__(self, "_optional", optional)

optional property

The inputs a binding may omit, which then take their defaults.

required property

The inputs a binding must supply, in order.

free_dims property

The shared dimension scope of all inputs.

is_concrete property

Whether all inputs have concrete dimensions.

__getitem__(names)

An input's type, or the selected inputs in this spec's order.

Parameters:

Name Type Description Default
names str or sequence of str

One input name, or a list or tuple of input names. A one-element list still selects an InputSpec.

required

Returns:

Type Description
TermSpec or InputSpec

The single input's type, or a spec retaining the selected inputs' order and optional flags.

Raises:

Type Description
KeyError

If a name is not an input.

TypeError

If the selection is not a string or a list or tuple of strings.

ValueError

If the list is empty, repeats a name, or contains overlapping paths.

Notes

Interim implementation detail: paths into a record input are not read yet. Select its input name to retain that entire record.

Source code in probpipe/core/_specs.py
def __getitem__(self, names: str | Sequence[str], /) -> TermSpec | InputSpec:
    """An input's type, or the selected inputs in this spec's order.

    Parameters
    ----------
    names : str or sequence of str
        One input name, or a list or tuple of input names. A one-element
        list still selects an InputSpec.

    Returns
    -------
    TermSpec or InputSpec
        The single input's type, or a spec retaining the selected inputs'
        order and optional flags.

    Raises
    ------
    KeyError
        If a name is not an input.
    TypeError
        If the selection is not a string or a list or tuple of strings.
    ValueError
        If the list is empty, repeats a name, or contains overlapping paths.

    Notes
    -----
    Interim implementation detail: paths into a record input are not read
    yet. Select its input name to retain that entire record.
    """
    requested = _as_paths(names, action="index InputSpec by")
    selected = (requested,) if isinstance(requested, str) else requested
    for name in selected:
        if name not in self._inputs:
            raise KeyError(
                _missing_path(name, owner="the input spec", available=self, requested=selected)
            )
    if isinstance(requested, str):
        return self._inputs[requested]
    return self._with_inputs(
        {name: spec for name, spec in self._inputs.items() if name in selected}, self._optional
    )

__contains__(name)

Whether name is a string naming an input; False for a list or tuple.

Source code in probpipe/core/_specs.py
def __contains__(self, name: object, /) -> bool:
    """Whether *name* is a string naming an input; False for a list or tuple."""
    return isinstance(name, str) and name in self._inputs

get(name, default=None)

The type of input name, or default when it is not an input name.

Source code in probpipe/core/_specs.py
def get(self, name: str, default: TermSpec | None = None, /) -> TermSpec | None:
    """The type of input *name*, or *default* when it is not an input name."""
    return self._inputs[name] if name in self else default

__and__(other)

Merge inputs in order of first appearance, checking shared types.

Parameters:

Name Type Description Default
other InputSpec

Inputs to append or match to this spec's inputs.

required

Returns:

Type Description
InputSpec

This spec's inputs followed by new inputs from other. A shared input is optional only when optional in both. Shared dimension bindings are applied throughout the result and not retained.

Raises:

Type Description
TypeError

If other is not an InputSpec. Convert an output spec with InputSpec(output_spec) before merging it.

ValueError

If shared types cannot describe one value, or a shared dimension would have two sizes.

Notes

Interim implementation detail: a shared input keeps its first type, with dimension bindings applied, rather than the unified type.

Source code in probpipe/core/_specs.py
def __and__(self, other: InputSpec, /) -> InputSpec:
    """Merge inputs in order of first appearance, checking shared types.

    Parameters
    ----------
    other : InputSpec
        Inputs to append or match to this spec's inputs.

    Returns
    -------
    InputSpec
        This spec's inputs followed by new inputs from *other*. A shared
        input is optional only when optional in both. Shared dimension
        bindings are applied throughout the result and not retained.

    Raises
    ------
    TypeError
        If *other* is not an InputSpec. Convert an output spec with
        InputSpec(output_spec) before merging it.
    ValueError
        If shared types cannot describe one value, or a shared dimension
        would have two sizes.

    Notes
    -----
    Interim implementation detail: a shared input keeps its first type,
    with dimension bindings applied, rather than the unified type.
    """
    if isinstance(other, OutputSpec):
        raise TypeError(
            "cannot merge an InputSpec with an OutputSpec. "
            "Convert the output spec first, as InputSpec(output_spec)"
        )
    if not isinstance(other, InputSpec):
        raise TypeError(
            f"cannot merge an InputSpec with {type(other).__name__}. Pass another InputSpec"
        )
    bindings: dict[str, int | str] = {}
    merged = dict(self._inputs)
    for name, spec in other.items():
        if name in merged:
            _unify_input_types(merged[name], spec, bindings, f"the input {name!r}")
        else:
            merged[name] = spec
    optional = frozenset(
        (self.optional - other.keys())
        | (other.optional - self.keys())
        | (self.optional & other.optional)
    )
    return self._with_inputs(
        {name: spec._substitute_dims(bindings) for name, spec in merged.items()}, optional
    )

__repr__()

Each input as a keyword, as the constructor takes it, then the optional inputs.

Source code in probpipe/core/_specs.py
def __repr__(self) -> str:
    """Each input as a keyword, as the constructor takes it, then the optional inputs."""
    text = term_repr("InputSpec", None, [(name, repr(spec)) for name, spec in self.items()])
    if not self._optional:
        return text
    names = ", ".join(repr(name) for name in self if name in self._optional)
    return f"{text}.with_optional({names})"

with_optional(*names)

The inputs with names optional, in addition to the inputs already optional.

Parameters:

Name Type Description Default
*names str

The inputs to mark optional.

()

Returns:

Type Description
InputSpec

A new spec of the same inputs.

Raises:

Type Description
KeyError

If a name is not an input.

Source code in probpipe/core/_specs.py
def with_optional(self, *names: str) -> InputSpec:
    """The inputs with *names* optional, in addition to the inputs already optional.

    Parameters
    ----------
    *names : str
        The inputs to mark optional.

    Returns
    -------
    InputSpec
        A new spec of the same inputs.

    Raises
    ------
    KeyError
        If a name is not an input.
    """
    unknown = [name for name in names if name not in self._inputs]
    if unknown:
        raise KeyError(f"with_optional(): {unknown_names('input', unknown, self._inputs)}")
    return self._with_inputs(self._inputs, self._optional | frozenset(names))

without(*names)

The inputs other than names, each optional input staying optional.

Parameters:

Name Type Description Default
*names str

Existing input names to remove. With none, all inputs are retained.

()

Returns:

Type Description
InputSpec

The retained inputs in declaration order, with their optional flags.

Raises:

Type Description
KeyError

If a name is not an input.

TypeError

If a name is not a string.

ValueError

If a name is malformed, repeated, or overlaps another name.

Source code in probpipe/core/_specs.py
def without(self, *names: str) -> InputSpec:
    """The inputs other than *names*, each optional input staying optional.

    Parameters
    ----------
    *names : str
        Existing input names to remove. With none, all inputs are retained.

    Returns
    -------
    InputSpec
        The retained inputs in declaration order, with their optional flags.

    Raises
    ------
    KeyError
        If a name is not an input.
    TypeError
        If a name is not a string.
    ValueError
        If a name is malformed, repeated, or overlaps another name.
    """
    names = _as_path_arguments(names, action="call InputSpec.without() with")
    unknown = [name for name in names if name not in self._inputs]
    if unknown:
        raise KeyError(f"without(): {unknown_names('input', unknown, self._inputs)}")
    return self._with_inputs(
        {name: spec for name, spec in self._inputs.items() if name not in names}, self._optional
    )

with_dim_sizes(**sizes)

Return the inputs with supplied sizes substituted in their shared scope.

Source code in probpipe/core/_specs.py
def with_dim_sizes(self, **sizes: int) -> InputSpec:
    """Return the inputs with supplied sizes substituted in their shared scope."""
    _dim_sizes(sizes)
    return self._with_inputs(
        {name: spec.with_dim_sizes(**sizes) for name, spec in self._inputs.items()},
        self._optional,
    )

with_dim_names(**names)

Return the inputs with simultaneous symbolic-dimension renaming.

Source code in probpipe/core/_specs.py
def with_dim_names(self, **names: str) -> InputSpec:
    """Return the inputs with simultaneous symbolic-dimension renaming."""
    _dim_renames(names)
    return self._with_inputs(
        {name: spec.with_dim_names(**names) for name, spec in self._inputs.items()},
        self._optional,
    )

bind_dims_from_value(value)

Bind all inputs against named values in one shared dimension scope.

Raises ValueError for missing/extra inputs or conflicting sizes.

Source code in probpipe/core/_specs.py
def bind_dims_from_value(self, value: Mapping[str, object]) -> InputSpec:
    """Bind all inputs against named values in one shared dimension scope.

    Raises ValueError for missing/extra inputs or conflicting sizes.
    """
    if not isinstance(value, Mapping):
        raise TypeError(
            f"InputSpec.bind_dims_from_value() expects a mapping, got {type(value).__name__}"
        )
    if self._inputs.keys() != value.keys():
        raise ValueError(
            f"values do not match the InputSpec inputs: {_name_mismatch(value, self)}"
        )
    bindings: dict[str, int] = {}
    for name, spec in self._inputs.items():
        spec._bind_dims_from_value(value[name], bindings, f"InputSpec{_PATH_SEP}{name}")
    return self._substitute_dims(bindings)

bind_dims_from_spec(other)

Bind against another input spec in one shared dimension scope.

Source code in probpipe/core/_specs.py
def bind_dims_from_spec(self, other: InputSpec) -> InputSpec:
    """Bind against another input spec in one shared dimension scope."""
    if not isinstance(other, InputSpec):
        raise TypeError(
            f"InputSpec.bind_dims_from_spec() expects an InputSpec, got {type(other).__name__}"
        )
    if self._inputs.keys() != other._inputs.keys():
        raise ValueError(
            f"the other InputSpec's inputs do not match these: {_name_mismatch(other, self)}"
        )
    bindings: dict[str, int] = {}
    for name, spec in self._inputs.items():
        _unify_specs(spec, other[name], bindings, f"InputSpec{_PATH_SEP}{name}")
    return self._substitute_dims(bindings)

OutputSpec(*args, **term) dataclass

The outputs of a function's return value, of the values a distribution is over, or of a batch's elements.

An output is a name under which a value can be read and passed on to an input of the same name. An OutputSpec holds a spec, term_spec, and its outputs follow from it, in one of two forms:

  • the positional form, OutputSpec(RecordSpec(mu=(), sigma=())), has one output per top-level name of a record (mu and sigma), or the outputs of a batch's elements. Over a distribution's or a conditional distribution's spec, as for a function that returns a distribution, it has no outputs; to pass the distribution on by name, put it in a record, OutputSpec(RecordSpec(params=d.spec));
  • the keyword form, OutputSpec(y=NumericArraySpec(())), names one output that holds the whole value.

An OutputSpec is indexed by path, as O["g/b"], and & merges two of them. It is not a mapping and not iterable; outputs lists the outputs.

Parameters:

Name Type Description Default
*args RecordSpec, DistributionSpec, ConditionalDistributionSpec, or BatchSpec

The positional form: the spec of the values, whose outputs are a record's top-level fields and groups, or the outputs of a batch's element, which is a record or a distribution; a distribution's or a conditional distribution's spec has none.

()
**term TermSpec, tuple, or None

The keyword form: one keyword, the output's name, over the spec of the whole value. None means the type is not known yet; with_term_spec gives it later. A tuple is converted to a NumericArraySpec of that shape.

{}

Raises:

Type Description
TypeError

If the positional form is not exactly one spec that has outputs, the forms are mixed, more than one keyword is given, or a record field lacks a spec.

ValueError

If no spec is given, or an output name is empty or contains /.

Examples:

>>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
>>> list(O.outputs)
['a', 'g']
>>> O["g/b"]
OutputSpec(b=NumericArraySpec(shape=()))
Notes

Only the form and the spec are stored; term_spec and outputs are derived from them. An output of a record is a field or group of the value.

Source code in probpipe/core/_specs.py
def __init__(self, *args: TermSpec, **term: TermSpec | tuple | None) -> None:
    if args:
        if term:
            raise TypeError("OutputSpec takes one positional spec or one keyword, not both")
        if len(args) != 1:
            raise TypeError(f"OutputSpec takes one positional spec, got {len(args)}")
        spec = args[0]
        if _exposed_kind(spec) is None:
            raise TypeError(
                f"OutputSpec cannot take a {type(spec).__name__} positionally; name a single "
                f"output with a keyword, such as OutputSpec(x=...). A positional spec must be "
                f"a RecordSpec, DistributionSpec, ConditionalDistributionSpec, or a BatchSpec "
                f"of one"
            )
        if isinstance(spec, RecordSpec):
            for name, child in spec.children.items():
                _check_output(name, child)
        name = None
    elif len(term) == 1:
        name, spec = next(iter(term.items()))
        if isinstance(spec, tuple):
            spec = _to_spec(spec)
        _check_output(name, spec, allow_hole=True)
    elif term:
        fields = ", ".join(f"{name}=..." for name in term)
        raise TypeError(
            f"OutputSpec takes one keyword, got {list(term)}; for several named outputs, "
            f"pass a record: OutputSpec(RecordSpec({fields}))"
        )
    else:
        raise ValueError("OutputSpec requires one keyword or an explicit RecordSpec")
    object.__setattr__(self, "_output_name", name)
    object.__setattr__(self, "_term_spec", spec)

term_spec property

The spec of the values described. None means the type is not known yet.

outputs property

Each output's name and spec, in order, as a read-only mapping.

is_concrete property

Whether the type is known and all its dimensions are concrete.

__repr__()

The OutputSpec as the constructor takes it: one keyword, or one positional spec.

Source code in probpipe/core/_specs.py
def __repr__(self) -> str:
    """The OutputSpec as the constructor takes it: one keyword, or one positional spec."""
    if self._output_name is None:
        return call_repr("OutputSpec", [repr(self._term_spec)])
    return term_repr("OutputSpec", None, [(self._output_name, repr(self._term_spec))])

__getitem__(paths)

The OutputSpec at a path, or of a list of paths.

Parameters:

Name Type Description Default
paths str, or list or tuple of str

A path, such as "g/b", or a list of paths. A tuple is read as a list of paths; a nested path is written with /.

required

Returns:

Type Description
OutputSpec

For one path, the OutputSpec of the value there: a single array or opaque value has one output named by the path's last name, as O["g/b"] is OutputSpec(b=...), and a record has its top-level names as outputs. For a list, the record of the chosen values, each at its own path, in this spec's order, as O[["g/b"]] is OutputSpec(RecordSpec(g=RecordSpec(b=...))). A list may name the one output of the keyword form, as OutputSpec(x=())[["x"]] is OutputSpec(RecordSpec(x=...)).

Raises:

Type Description
KeyError

If a path is not a path of this OutputSpec's record.

TypeError

If paths is neither a string nor a list or tuple of strings, or this OutputSpec has no paths to select, as over a single array or a distribution.

ValueError

If a path is empty or has an empty name, or a list of paths is empty, names a path twice, or holds a path inside another.

Notes

As an interim implementation detail, the name of the one output of the keyword form gives this OutputSpec itself, as Normal("x", 0.0, 1.0)["x"] gives the distribution itself, until an accessor of an output replaces both readings; a value with no paths has no path to select.

Examples:

>>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
>>> O["g"]
OutputSpec(NumericRecordSpec(b=(), c=()))
>>> O[["g/b"]]
OutputSpec(NumericRecordSpec(g=NumericRecordSpec(b=())))
Source code in probpipe/core/_specs.py
def __getitem__(self, paths: str | Sequence[str], /) -> OutputSpec:
    """The OutputSpec at a path, or of a list of paths.

    Parameters
    ----------
    paths : str, or list or tuple of str
        A path, such as ``"g/b"``, or a list of paths. A tuple is read as a
        list of paths; a nested path is written with ``/``.

    Returns
    -------
    OutputSpec
        For one path, the OutputSpec of the value there: a single array or
        opaque value has one output named by the path's last name, as
        ``O["g/b"]`` is ``OutputSpec(b=...)``, and a record has its
        top-level names as outputs. For a list, the record of the chosen
        values, each at its own path, in this spec's order, as ``O[["g/b"]]``
        is ``OutputSpec(RecordSpec(g=RecordSpec(b=...)))``. A list may name
        the one output of the keyword form, as ``OutputSpec(x=())[["x"]]``
        is ``OutputSpec(RecordSpec(x=...))``.

    Raises
    ------
    KeyError
        If a path is not a path of this OutputSpec's record.
    TypeError
        If *paths* is neither a string nor a list or tuple of strings, or
        this OutputSpec has no paths to select, as over a single array or
        a distribution.
    ValueError
        If a path is empty or has an empty name, or a list of paths is
        empty, names a path twice, or holds a path inside another.

    Notes
    -----
    As an interim implementation detail, the name of the one output of the
    keyword form gives this OutputSpec itself, as ``Normal("x", 0.0,
    1.0)["x"]`` gives the distribution itself, until an accessor of an
    output replaces both readings; a value with no paths has no path to
    select.

    Examples
    --------
    >>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
    >>> O["g"]
    OutputSpec(NumericRecordSpec(b=(), c=()))
    >>> O[["g/b"]]
    OutputSpec(NumericRecordSpec(g=NumericRecordSpec(b=())))
    """
    read_paths = _read_paths(
        self,
        paths,
        owner="the output spec",
        values_word="values",
        action="index the output spec by",
    )
    if isinstance(read_paths, str):
        if read_paths == self._output_name:
            return self
        node_spec = cast(RecordSpec, _path_record(self))[read_paths]
        return _output_spec_at(node_spec, _last_name(read_paths))
    if self._term_spec is None:
        raise TypeError(
            f"cannot index the output spec by {list(read_paths)}, since {_type_not_known(self)}"
        )
    return OutputSpec(_output_record(self)[read_paths])

__contains__(path)

Whether path is a string and self[path] succeeds.

As [] does, it reads the name of the keyword form's one output as an interim implementation detail.

Source code in probpipe/core/_specs.py
def __contains__(self, path: object, /) -> bool:
    """Whether *path* is a string and ``self[path]`` succeeds.

    As ``[]`` does, it reads the name of the keyword form's one output as
    an interim implementation detail.
    """
    return _has_path(self, path)

__iter__()

Not supported: an OutputSpec is not a mapping; iterate over its outputs.

Raises:

Type Description
TypeError

Always.

Source code in probpipe/core/_specs.py
def __iter__(self) -> NoReturn:
    """Not supported: an OutputSpec is not a mapping; iterate over its ``outputs``.

    Raises
    ------
    TypeError
        Always.
    """
    raise TypeError(
        "cannot iterate over an OutputSpec. Iterate over its outputs instead, as "
        "list(spec.outputs)"
    )

without(*paths)

This OutputSpec without the values at some paths.

Parameters:

Name Type Description Default
*paths str

The paths to remove, one per argument; a group left empty goes too.

()

Returns:

Type Description
OutputSpec

The rest, each value at its own path, in the same form.

Raises:

Type Description
KeyError

If a path is not a path of this OutputSpec's record.

TypeError

If a path is not a string, or this OutputSpec has no paths to remove, as over a single array or a distribution.

ValueError

If nothing would remain, or the paths name a path twice or a path inside another.

Examples:

>>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
>>> O.without("g/c")
OutputSpec(NumericRecordSpec(a=(), g=NumericRecordSpec(b=())))
Source code in probpipe/core/_specs.py
def without(self, *paths: str) -> OutputSpec:
    """This OutputSpec without the values at some paths.

    Parameters
    ----------
    *paths : str
        The paths to remove, one per argument; a group left empty goes too.

    Returns
    -------
    OutputSpec
        The rest, each value at its own path, in the same form.

    Raises
    ------
    KeyError
        If a path is not a path of this OutputSpec's record.
    TypeError
        If a path is not a string, or this OutputSpec has no paths to
        remove, as over a single array or a distribution.
    ValueError
        If nothing would remain, or the paths name a path twice or a path
        inside another.

    Examples
    --------
    >>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
    >>> O.without("g/c")
    OutputSpec(NumericRecordSpec(a=(), g=NumericRecordSpec(b=())))
    """
    read_paths = _as_path_arguments(paths, action="call without() with")
    for path in read_paths:
        if not _has_path(self, path):
            raise _paths_error(
                self,
                path,
                owner="the output spec",
                values_word="values",
                action="remove",
                after_path=" from the output spec",
            )
    if self._output_name in read_paths:
        raise ValueError(
            f"cannot remove {self._output_name!r} from the output spec, since it names the "
            f"whole value and nothing would remain"
        )
    remaining_record = _output_record(self).without(*read_paths)
    if self._output_name is None:
        return OutputSpec(remaining_record)
    return OutputSpec(**{self._output_name: remaining_record.children[self._output_name]})

__and__(other)

Merge two OutputSpecs: the outputs of both, this one's first.

Parameters:

Name Type Description Default
other OutputSpec

The outputs to add after this spec's.

required

Returns:

Type Description
OutputSpec

The positional form over the record of both specs' outputs; the output y of the keyword form becomes the field y.

Raises:

Type Description
TypeError

If either spec's type is not known yet, or it is in the positional form over distributions, which have no outputs, or over batches, whose outputs are not read as one record yet. Wrap such values under a name to merge them.

ValueError

If an output name is in both.

Examples:

>>> OutputSpec(x=NumericArraySpec(())) & OutputSpec(RecordSpec(a=()))
OutputSpec(NumericRecordSpec(x=(), a=()))
Source code in probpipe/core/_specs.py
def __and__(self, other: OutputSpec, /) -> OutputSpec:
    """Merge two OutputSpecs: the outputs of both, this one's first.

    Parameters
    ----------
    other : OutputSpec
        The outputs to add after this spec's.

    Returns
    -------
    OutputSpec
        The positional form over the record of both specs' outputs; the
        output ``y`` of the keyword form becomes the field ``y``.

    Raises
    ------
    TypeError
        If either spec's type is not known yet, or it is in the
        positional form over distributions, which have no outputs, or over
        batches, whose outputs are not read as one record yet. Wrap such
        values under a name to merge them.
    ValueError
        If an output name is in both.

    Examples
    --------
    >>> OutputSpec(x=NumericArraySpec(())) & OutputSpec(RecordSpec(a=()))
    OutputSpec(NumericRecordSpec(x=(), a=()))
    """
    if not isinstance(other, OutputSpec):
        return NotImplemented
    return OutputSpec(
        _merged_output_record(
            (self, other),
            owners=("the left output spec", "the right output spec"),
            values_word="values",
        )
    )

default(term_spec, *, output_name) classmethod

The OutputSpec ProbPipe uses for values of term_spec when none is given.

It is OutputSpec(term_spec) if term_spec is a RecordSpec, whose fields and groups become the outputs, and OutputSpec(**{output_name: term_spec}) otherwise.

Parameters:

Name Type Description Default
term_spec TermSpec

The spec of the values.

required
output_name str

The name of the one output when term_spec is not a RecordSpec.

required

Returns:

Type Description
OutputSpec

The positional form for a record, and the keyword form otherwise.

Raises:

Type Description
ValueError

If term_spec is not a record and output_name is not a valid output name.

Source code in probpipe/core/_specs.py
@classmethod
def default(cls, term_spec: TermSpec, *, output_name: str) -> OutputSpec:
    """The OutputSpec ProbPipe uses for values of *term_spec* when none is given.

    It is ``OutputSpec(term_spec)`` if *term_spec* is a ``RecordSpec``, whose
    fields and groups become the outputs, and
    ``OutputSpec(**{output_name: term_spec})`` otherwise.

    Parameters
    ----------
    term_spec : TermSpec
        The spec of the values.
    output_name : str
        The name of the one output when *term_spec* is not a ``RecordSpec``.

    Returns
    -------
    OutputSpec
        The positional form for a record, and the keyword form otherwise.

    Raises
    ------
    ValueError
        If *term_spec* is not a record and *output_name* is not a valid
        output name.
    """
    if isinstance(term_spec, RecordSpec):
        return cls(term_spec)
    return cls(**{output_name: term_spec})

with_term_spec(term_spec)

This OutputSpec with its spec completed from term_spec.

Where this OutputSpec's spec is None, which means the type is not known yet, it becomes term_spec. Otherwise the declared spec must unify with term_spec, and the result keeps the names and the form and stores their unification: a numeric array keeps its declared dtype and support and takes term_spec's where the declared spec leaves them unset, and a declared dimension name binds to the size term_spec gives. A record unifies field by field, and an opaque spec takes the known type and meta. Any other kind takes term_spec.

Parameters:

Name Type Description Default
term_spec TermSpec

The spec of the actual values.

required

Returns:

Type Description
OutputSpec

The completed OutputSpec.

Raises:

Type Description
TypeError

If this OutputSpec is in the positional form and term_spec is not a spec of the same kind, such as a RecordSpec for a record.

ValueError

If the declared spec does not unify with term_spec.

Source code in probpipe/core/_specs.py
def with_term_spec(self, term_spec: TermSpec, /) -> OutputSpec:
    """This OutputSpec with its spec completed from *term_spec*.

    Where this OutputSpec's spec is None, which means the type is not known
    yet, it becomes *term_spec*. Otherwise the declared spec must unify with
    *term_spec*, and the result keeps the names and the form and stores their
    unification: a numeric array keeps its declared dtype and support and
    takes *term_spec*'s where the declared spec leaves them unset, and a
    declared dimension name binds to the size *term_spec* gives. A record
    unifies field by field, and an opaque spec takes the known type and
    ``meta``. Any other kind takes *term_spec*.

    Parameters
    ----------
    term_spec : TermSpec
        The spec of the actual values.

    Returns
    -------
    OutputSpec
        The completed OutputSpec.

    Raises
    ------
    TypeError
        If this OutputSpec is in the positional form and *term_spec* is not a
        spec of the same kind, such as a ``RecordSpec`` for a record.
    ValueError
        If the declared spec does not unify with *term_spec*.
    """
    kind = None if self._output_name is not None else _exposed_kind(self._term_spec)
    if kind is not None and _exposed_kind(term_spec) != kind:
        raise TypeError(
            f"with_term_spec() needs a {_EXPOSED_SPECS[kind]} for an OutputSpec over "
            f"{_EXPOSED_OF[kind]}, got {type(term_spec).__name__}"
        )
    if self._term_spec is not None:
        bindings: dict[str, int] = {}
        root = _root_path(self._output_name, kind)
        _unify_specs(self._term_spec, term_spec, bindings, root)
        term_spec = _unification(self._term_spec, term_spec, bindings)
    return self._with_term_spec(term_spec)

rename(renames=None, /, **keyword_renames)

Rename or move nodes of this OutputSpec by their paths, old -> new.

A path starts with an output. In the positional form over a record, the paths are the record's; in the keyword form, a path is the output's name followed by a path within its value. Each key is the exact path of a node and each target its new exact path, under the rule of rename. The result keeps the form. In the positional form a move may add or remove an output. In the keyword form the output is renamed in place and the fields of its value stay under it, so a field moves only within the output.

Parameters:

Name Type Description Default
renames Mapping of str to str

The new path of each node, keyed by the node's path.

None
**keyword_renames str

The new path of each output, keyed by the output's name.

{}

Returns:

Type Description
OutputSpec

The renamed OutputSpec.

Raises:

Type Description
KeyError

If a key is not a path of this OutputSpec.

TypeError

As rename raises it.

ValueError

As rename raises it, or if the keyword form's output moves into a group or one of its fields moves out of it.

Source code in probpipe/core/_specs.py
def rename(
    self, renames: Mapping[str, str] | None = None, /, **keyword_renames: str
) -> OutputSpec:
    """Rename or move nodes of this OutputSpec by their paths, ``old -> new``.

    A path starts with an output. In the positional form over a record, the
    paths are the record's; in the keyword form, a path is the output's name
    followed by a path within its value. Each key is the exact path of a node
    and each target its new exact path, under the rule of
    :meth:`~probpipe.core.named_tree.NamedTree.rename`. The result
    keeps the form. In the positional form a move may add or remove an
    output. In the keyword form the output is renamed in place and the
    fields of its value stay under it, so a field moves only within the
    output.

    Parameters
    ----------
    renames : Mapping of str to str, optional
        The new path of each node, keyed by the node's path.
    **keyword_renames : str
        The new path of each output, keyed by the output's name.

    Returns
    -------
    OutputSpec
        The renamed OutputSpec.

    Raises
    ------
    KeyError
        If a key is not a path of this OutputSpec.
    TypeError
        As :meth:`~probpipe.core.named_tree.NamedTree.rename` raises it.
    ValueError
        As :meth:`~probpipe.core.named_tree.NamedTree.rename` raises
        it, or if the keyword form's output moves into a group or one of its
        fields moves out of it.
    """
    spec = self._term_spec
    output_name = self._output_name
    if output_name is None:
        return OutputSpec(_renamed_exposed(cast(TermSpec, spec), renames, keyword_renames))
    # A whole term's paths are those of the record of its one output.
    outputs = RecordSpec({output_name: OpaqueSpec() if spec is None else spec})
    resolved_renames = outputs._resolve_path_renames(renames, keyword_renames)
    renamed_output_name = resolved_renames.get(output_name, output_name)
    if _PATH_SEP in renamed_output_name:
        raise ValueError(
            f"cannot rename {output_name!r} to {renamed_output_name!r}: rename() can "
            f"rename the output of the keyword form but cannot move it into a group. "
            f"Choose a name without {_PATH_SEP!r}."
        )
    prefix = renamed_output_name + _PATH_SEP
    for source, target in resolved_renames.items():
        if source != output_name and not target.startswith(prefix):
            owner = (
                repr(output_name)
                if renamed_output_name == output_name
                else f"{output_name!r}, renamed to {renamed_output_name!r},"
            )
            raise ValueError(
                f"cannot move {source!r} to {target!r}: fields of {owner} must stay "
                f"under {prefix!r}"
            )
    ((name, term),) = outputs.rename(resolved_renames).children.items()
    return OutputSpec(**{name: None if spec is None else term})

with_dim_sizes(**sizes)

This OutputSpec with dimension names bound to sizes, keeping its form.

Source code in probpipe/core/_specs.py
def with_dim_sizes(self, **sizes: int) -> OutputSpec:
    """This OutputSpec with dimension names bound to sizes, keeping its form."""
    _dim_sizes(sizes)
    term_spec = self._term_spec
    return self._with_term_spec(
        None if term_spec is None else term_spec.with_dim_sizes(**sizes)
    )

with_dim_names(**names)

This OutputSpec with dimension names renamed, keeping its form.

Source code in probpipe/core/_specs.py
def with_dim_names(self, **names: str) -> OutputSpec:
    """This OutputSpec with dimension names renamed, keeping its form."""
    _dim_renames(names)
    term_spec = self._term_spec
    return self._with_term_spec(
        None if term_spec is None else term_spec.with_dim_names(**names)
    )

Constraints

Constraint

Describes the support of a distribution (the set of valid values).

check(value)

Return a boolean array indicating which elements satisfy the constraint.

A support that is a subset of the reals contains a complex entry only where its imaginary part is zero and its real part is in the support.

Source code in probpipe/core/constraints.py
def check(self, value: ArrayLike) -> Array:
    """Return a boolean array indicating which elements satisfy the constraint.

    A support that is a subset of the reals contains a complex entry only
    where its imaginary part is zero and its real part is in the support.
    """
    raise NotImplementedError

real = _Real() module-attribute

The support of all finite real numbers.

positive = _Positive() module-attribute

The support of the strictly positive reals, (0, inf).

non_negative = _NonNegative() module-attribute

The support of the non-negative reals, [0, inf).

non_negative_integer = _NonNegativeInteger() module-attribute

The support of the non-negative integers, {0, 1, 2, ...}.

boolean = _Boolean() module-attribute

The support of the binary values {0, 1}.

unit_interval = _UnitInterval() module-attribute

The support of the closed unit interval, [0, 1].

simplex = _Simplex() module-attribute

The probability simplex: non-negative vectors that sum to one along the last axis.

positive_definite = _PositiveDefinite() module-attribute

The support of the positive-definite matrices.

sphere = _Sphere() module-attribute

The unit sphere: vectors of unit Euclidean norm along the last axis.

interval(low, high)

The support of the closed interval [low, high].

Source code in probpipe/core/constraints.py
def interval(low: ArrayLike, high: ArrayLike) -> _Interval:
    """The support of the closed interval ``[low, high]``."""
    return _Interval(low, high)

greater_than(lower_bound)

The support of the values strictly greater than lower_bound.

Source code in probpipe/core/constraints.py
def greater_than(lower_bound: ArrayLike) -> _GreaterThan:
    """The support of the values strictly greater than *lower_bound*."""
    return _GreaterThan(lower_bound)

integer_interval(low, high)

The support of the integers in the closed interval [low, high].

Source code in probpipe/core/constraints.py
def integer_interval(low: ArrayLike, high: ArrayLike) -> _IntegerInterval:
    """The support of the integers in the closed interval ``[low, high]``."""
    return _IntegerInterval(low, high)

Bijectors onto a support

bijector_for returns the canonical bijector from an unconstrained space onto a constraint's support. register_bijector, on Registries for extensions, registers the bijector for a constraint.

bijector_for(constraint)

The canonical bijector from ℝⁿ onto constraint's support.

The factory registered for constraint itself applies first, and then the one registered for the nearest type in its method-resolution order.

Parameters:

Name Type Description Default
constraint Constraint

The support to map onto.

required

Returns:

Type Description
Function

A map onto the support that claims SupportsInverse and SupportsLogDetJacobian.

Raises:

Type Description
ResolutionError

If no factory is registered for constraint or its types, or the factory's map does not claim both capabilities.

TypeError

If the factory returns neither a Function nor a backend bijector.

MathematicalDomainError

If constraint is a support onto which no smooth bijector exists, such as a discrete support or the unit sphere.

Source code in probpipe/functions/_reparameterization.py
def bijector_for(constraint: Constraint) -> Function:
    """The canonical bijector from ℝⁿ onto *constraint*'s support.

    The factory registered for *constraint* itself applies first, and then the
    one registered for the nearest type in its method-resolution order.

    Parameters
    ----------
    constraint : Constraint
        The support to map onto.

    Returns
    -------
    Function
        A map onto the support that claims ``SupportsInverse`` and
        ``SupportsLogDetJacobian``.

    Raises
    ------
    ResolutionError
        If no factory is registered for *constraint* or its types, or the
        factory's map does not claim both capabilities.
    TypeError
        If the factory returns neither a ``Function`` nor a backend bijector.
    MathematicalDomainError
        If *constraint* is a support onto which no smooth bijector exists, such
        as a discrete support or the unit sphere.
    """
    factory = _factory(constraint)
    returned = factory(constraint)
    if not isinstance(returned, (Function, tfb.Bijector)):
        raise TypeError(
            f"the bijector factory registered for {constraint!r} returned "
            f"{type_name(returned)}; it must return a Function or a TFP bijector"
        )
    bijector = _as_bijector(returned, image=constraint)
    missing = [
        claim
        for claim, holds in (
            ("SupportsInverse", is_invertible(bijector)),
            ("SupportsLogDetJacobian", isinstance(bijector, SupportsLogDetJacobian)),
        )
        if not holds
    ]
    if missing:
        raise ResolutionError(
            f"the bijector {bijector.label!r} registered for {constraint!r} must support "
            f"SupportsInverse and SupportsLogDetJacobian, but lacks {' and '.join(missing)}"
        )
    return bijector