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.

Values and records

This page documents the value kinds, such as Record and NumericArray, their batches, and the linear operators. The specs that declare these values are on Input and output specs, and the callable kind Function is on Functions.

Records

Record(fields, /, *, label=None, event_template=None, _validate_leaves=True)

Bases: NamedTree[Any], TrackedTerm, Annotated

A single structured value with metadata.

A Record holds a single concrete value: an ordered, named collection of fields. Every record stores its type as a RecordSpec that encodes the structure of the value: the names, how the fields are stored, and specs on the fields themselves. spec and event_template return the same stored object. A record is immutable and its spec is fixed at construction.

A named collection of values. A Record is a NamedTree, so it inherits a mapping/dictionary-like interface over the fields it stores: a field is accessed as record["a"], and a nested field by its path, record["a/b/c"]. len(record) is the number of fields, and record.keys() / record.values() / record.items() iterate the paths / field values / pairs. The canonical field order is depth-first in insertion order. An empty record requires an explicit root label. ::

r = Record(
    {
        "x": 1.5,
        "y": Record(
            {"a": 0.0, "b": 2.0},
            label="y",
        ),
    },
    label="r",
)
r["x"]  # 1.5
r["y/a"]  # 0.0   — a nested leaf, by its path
len(r)  # 3
list(r.keys())  # ['x', 'y/a', 'y/b']

Tree structure. A Record can equally be viewed as a tree, with the fields at its leaves. The only allowed internal node is a nested Record, a group; every other value is interpreted as a leaf. Names are unique within each node, so every node has a unique /-path. The structure of the node record[path] is described by the matching spec record.event_template[path]. [] takes a path or a list of paths: one path gives the node there, a field's value or a group's record, and a list or a tuple of paths gives the record cut down to those nodes, each at its own path and in this record's order, labeled by the paths. p in record is true when record[p] gives a node, so it holds for a group, which keys() does not list. children gives the one-level name -> child view. ::

r["y"]            # Record(a=0.0, b=2.0)  — a group
r["y"]["a"]       # 0.0, the same node as r["y/a"]
r["x", "y/b"]     # Record {x, y: {b}}, labeled "(x, y/b)"
r[["y"]]          # Record {y: {a, b}}: a list of one path keeps the name
"y" in r          # True
dict(r.children)  # {'x': 1.5, 'y': Record(a=0.0, b=2.0)}

Structure encoded by the event template. event_template always reflects the structure of the stored value. Because a RecordSpec is itself a NamedTree, its tree mirrors the record's exactly: each nested Record corresponds to a nested RecordSpec, and each field value corresponds to a value spec (an array to an NumericArraySpec, any non-array to an OpaqueSpec, and so on). ::

r.event_template
# NumericRecordSpec(x=(), y=NumericRecordSpec(a=(), b=()))
r.event_template["y/a"]  # NumericArraySpec(shape=())  — the spec for r["y/a"]

# A record's group and its template's group stay in lock-step:
r["y"].event_template == r.event_template["y"]  # True

# Each field value maps to a value spec by type:
Record(
    {"vec": jnp.zeros(3), "label": "fox"},
    label="r",
).event_template
# RecordSpec(vec=(3,), label=OpaqueSpec(type=str))   — array -> NumericArraySpec

Metadata: identity and annotations. A record is a tracked term: it is TrackedTerm, carrying a human-readable label and, optionally, a provenance, the Provenance describing how it was created, attached write-once via with_provenance. It is also Annotated, so free-form annotations may be attached after construction.

Construction and validation. A record is built from a flat mapping of key/field pairs — either as keyword arguments or as a single positional mapping, but not both. Mappings are never leaves: a mapping value denotes tree structure, so a plain dict passed as a field value is materialised into a nested subtree — never stored as a leaf — whether it appears as a keyword value or nested inside a positional mapping. When every leaf is a numeric array (so the carried template is a NumericRecordSpec), Record(...) auto-promotes to NumericRecord, mirroring the RecordSpec promotion; the numeric axis is re-derived whenever a transform constructs a new record, so an edit that removes the last non-numeric leaf promotes the result and one that introduces a non-numeric leaf demotes it. An explicit non-numeric event_template keeps the result a plain Record. ::

# All three build the same record:
Record(
    {
        "x": 1.5,
        "y": Record(
            {"a": 0.0, "b": 2.0},
            label="y",
        ),
    },
    label="r",
)
Record(
    {"x": 1.5, "y/a": 0.0, "y/b": 2.0},
    label="r",
)
Record(
    {"x": 1.5, "y": {"a": 0.0, "b": 2.0}},
    label="r",
)

When an event_template is supplied it is validated against the value's structure, and any mismatch in tree shape or field/spec kind raises ValueError. When omitted, the template is inferred via RecordSpec.infer_from; inference recovers the tree structure but is lossy on the value specs (e.g. it cannot recover a FunctionSpec's input / output structure). ::

Record(
    {"a": 1.0},
    event_template=RecordSpec(a=(), b=()),
    label="r",
)
# ValueError: event_template fields ['a', 'b'] do not match record fields ['a'] ...

Equality and hashing. Two records are equal when they share a concrete class (both Record, or both NumericRecord), have equal event_template\ s, and are field-by-field equal. Because equality includes the template, whether an identity transform round-trips to an equal record depends on how it treats the template. A transform that threads the template through — replace / merge / without, or reconstruction via Record.from_field_values — preserves it exactly and compares equal. A transform that instead re-infers the template — map / map_with_keys, which rebuild the result and re-infer its specs — compares equal only when inference recovers the original template, for instance when that template was itself inferred (the record was built without an explicit event_template). Inference is lossy: RecordSpec.infer_from cannot recover a NumericArraySpec's dtype / support, an OpaqueSpec's meta, etc., so an identity map of a record carrying a richer explicit template does not compare equal::

r.map(lambda x: x) == r   # True only if r's template is inference-recoverable

Hashing is structural: a record's hash combines its class, its field names, and each field's shape and dtype (nested records hash recursively; an opaque leaf falls back to its type). It fingerprints the record's structure rather than its data, so records that share a structure fall in the same hash bucket.

Parameters:

Name Type Description Default
fields Mapping

Field values in canonical first-appearance order. A mapping value becomes a nested record. Slash-delimited keys declare nested paths. Fields named label, name, and event_template remain ordinary mapping keys.

required
label str

The root's display alias. Defaults to record(field,...) from the declared top-level fields. An empty record requires an explicit label.

None
event_template RecordSpec

The authoritative schema. Defaults to the schema inferred from the fields. A supplied schema is validated and its shared dimensions are bound jointly.

None
_validate_leaves bool

Whether to validate leaves against a supplied template. Internal numerical reconstruction skips this check. Numeric records still require numeric leaves.

True

Raises:

Type Description
ValueError

If the field paths conflict or a supplied event_template disagrees with the fields or their values.

TypeError

If fields is not a mapping; if it is a string and label is omitted, which is the earlier label-first form; if a field key is not a string; or if fields is empty and label is omitted, which leaves nothing to derive the label from.

Notes

A Record is a registered JAX PyTree, but the tree from JAX's perspective may differ from the tree from ProbPipe's perspective. ProbPipe only allows nested Records to be internal nodes, while JAX also descends into container leaves like tuples and lists (which Record views as single opaque leaves). A dict is never a leaf — a mapping denotes tree structure — so it does not arise as a container leaf here. This implies that JAX sees a tree with finer structure, so that methods like jax.tree_util.tree_flatten / tree_leaves / tree_map (and jit / vmap / grad) descend into nested Record\s and into container leaves like tuples and lists. It is thus typically best practice to use the custom Record functionality for traversing the fields. The above JAX functions will work, but users must be aware that they will traverse the finer tree. The two notions of the tree coincide when every field is an array (e.g. NumericRecord).

The PyTree registration's children are the field values and its static aux data is the spec alone, so the declared type survives a tree_flatten / tree_unflatten round-trip and two records that differ only in their labels have equal treedefs and share a compilation. The label, the expression, provenance, and annotations do not cross a JAX transform boundary: a record rebuilt from its leaves is labeled <no description> until a result boundary labels it, and with_label relabels it otherwise. On a NumericRecord, the flatten boundary is also where native leaves convert to jax.Array, so a value that crosses a JAX transform comes back with bare-array leaves.

Source code in probpipe/core/record.py
def __init__(
    self,
    fields: Mapping[str, Any],
    /,
    *,
    label: str | None = None,
    event_template: RecordSpec | None = None,
    _validate_leaves: bool = True,
):
    if not isinstance(fields, Mapping):
        raise TypeError(_not_a_field_mapping(type(self).__name__, fields))
    field_inputs = _unflatten_paths(fields)
    label = _derived_record_name(field_inputs) if label is None else label

    if event_template is not None and event_template.free_dims and _validate_leaves:
        event_template, _ = _unify_record_spec_with_value(
            event_template, field_inputs, context=f"Record {label!r}"
        )

    field_map: dict[str, _FieldValue] = {}
    for field_name, value in field_inputs.items():
        sub_template: RecordSpec | None = None
        if event_template is not None:
            template_child = event_template.children.get(field_name)
            if isinstance(template_child, RecordSpec):
                sub_template = template_child
        try:
            if isinstance(value, Mapping):
                # A mapping value is nested tree structure, never a leaf:
                # materialise it into a child collection.
                field_map[field_name] = type(self)(
                    value,
                    event_template=sub_template,
                    label=field_name,
                )
            elif (
                sub_template is not None
                and isinstance(value, Record)
                # A batched child (RecordBatch) carries its own template and
                # is stored verbatim; ``batch_shape`` is duck-typed because
                # importing RecordBatch here would be circular.
                and not hasattr(value, "batch_shape")
            ):
                if value.event_template is sub_template:
                    # The child already carries this exact template object
                    # (e.g. built by ``from_field_values`` or threaded from
                    # the producing generator) — reuse it verbatim, keeping
                    # its provenance and native leaves. Identity, not ``==``:
                    # the point is to adopt the *supplied* template object,
                    # and an equal-but-distinct child template must still be
                    # rebuilt through it.
                    field_map[field_name] = self._named_by_key(field_name, value)
                else:
                    field_map[field_name] = type(value)(
                        dict(value._tree),
                        event_template=sub_template,
                        label=field_name,
                    )
            else:
                if isinstance(value, Record):
                    value = self._named_by_key(field_name, value)
                else:
                    self._check_leaf(field_name, value)
                field_map[field_name] = value
        except ValueError as error:
            raise ValueError(f"at {field_name!r}: {error}") from None

    object.__setattr__(
        self, "_tree", {key: _read_only(value) for key, value in field_map.items()}
    )
    self._init_tracked(label)
    if event_template is None:
        event_template = RecordSpec.infer_from(field_map)
    else:
        self._validate_event_template(event_template, check_leaf_values=_validate_leaves)
        # Store fields in the template's field order so iteration,
        # ``values()``, ``from_field_values``, and pytree unflatten all
        # agree on one canonical order (the template is authoritative).
        # Validation above confirmed the key sets match; when the template
        # was inferred the order already matches, so this only reorders a
        # record built with an explicitly out-of-order template — matching
        # how ``RecordBatch`` canonicalizes to its template.
        if tuple(field_map) != tuple(event_template.children):
            object.__setattr__(
                self, "_tree", {k: field_map[k] for k in event_template.children}
            )
    object.__setattr__(self, "_spec", event_template)

spec property

This record's own RecordSpec — the single stored source of its type.

Fixed at construction and always present. The schema is the kind spec itself; event_template exposes the same object.

event_template property

The authoritative RecordSpec describing this value's structure.

Returns the same object as spec, fixed at construction and always present. When a declaration was supplied (carried forward from the producing generator) it describes that structure; otherwise one was inferred from the field data at construction (via RecordSpec.infer_from).

Notes

Inference is a lossy fallback (it cannot recover a NumericArraySpec's dtype / support, an OpaqueSpec's meta, or declarations not carried by an untracked value), so both round trips out of this process carry the declaration rather than re-deriving it: the spec rides in the JAX pytree aux data, and __reduce__ serializes it. A value reconstructed by tree_unflatten or by pickle.loads carries this same structure.

raw property

The stored representation: the nested mapping of raw leaves.

A leaf is held in native form, so its raw value is the leaf itself, and a tracked term held as a leaf, such as a law, gives its own raw. An interior node gives the nested mapping of the raw leaves beneath it. A node's stored form is read from the mapping, as record.raw["g"]["x"], which also works inside a JAX trace. A field's view has a raw of its own, record["g/x"].raw, which presents the leaf as the view's kind does, so a Python scalar becomes an array, and inside a trace indexing returns the traced leaf itself, which has no raw.

The leaves are resolved on the first read and kept, so a stored law is detached once, and each read returns a new dict over them that the caller may change. A record has a raw form only when every leaf has one, so a leaf whose raw form raises, such as a field view with no exact marginal, makes the read raise. A record holding a traced leaf keeps nothing.

select(*paths, **mapping)

The nodes at paths in a plain dict, keyed for splatting into a call.

A positional path is keyed by its last name, so select("a", "g/c") gives {"a": self["a"], "c": self["g/c"]}, and a keyword names the key, so select(x="g/c") gives {"x": self["g/c"]}. A path to a group gives the group's record. The result is a value-only dict, not a Record, and carries no schema.

Usage::

predict(**params.select("r", "K"), x=x_grid)
predict(**params.select(growth_rate="r"), x=x_grid)

Parameters:

Name Type Description Default
*paths str

Paths to select, each keyed by its last name in the result.

()
**mapping str

Paths to select, each keyed by its keyword in the result.

{}

Returns:

Type Description
dict of str to Any

The node at each path, the positional paths first.

Raises:

Type Description
KeyError

If a path is not a path of this record.

TypeError

If a path is not a string.

ValueError

If a path is empty or has an empty name, or two entries would take the same key, as select("s1/theta", "s2/theta") would.

Source code in probpipe/core/record.py
def select(self, *paths: str, **mapping: str) -> dict[str, _FieldValue]:
    """The nodes at *paths* in a plain ``dict``, keyed for splatting into a call.

    A positional path is keyed by its last name, so ``select("a", "g/c")``
    gives ``{"a": self["a"], "c": self["g/c"]}``, and a keyword names the
    key, so ``select(x="g/c")`` gives ``{"x": self["g/c"]}``. A path to a
    group gives the group's record. The result is a value-only ``dict``,
    not a ``Record``, and carries no schema.

    Usage::

        predict(**params.select("r", "K"), x=x_grid)
        predict(**params.select(growth_rate="r"), x=x_grid)

    Parameters
    ----------
    *paths : str
        Paths to select, each keyed by its last name in the result.
    **mapping : str
        Paths to select, each keyed by its keyword in the result.

    Returns
    -------
    dict of str to Any
        The node at each path, the positional paths first.

    Raises
    ------
    KeyError
        If a path is not a path of this record.
    TypeError
        If a path is not a string.
    ValueError
        If a path is empty or has an empty name, or two entries would take
        the same key, as ``select("s1/theta", "s2/theta")`` would.
    """
    return {key: self[path] for key, path in _keyed_paths(paths, mapping).items()}

select_all()

Return every top-level field as a dict, for splatting into a call.

Sugar for select over the one-level names (self.children). On the batch and distribution subclasses, whose __getitem__ returns a per-field view, the dict holds those views, so the result can be splatted back into a Function field-by-field.

Source code in probpipe/core/record.py
def select_all(self) -> dict[str, _FieldValue]:
    """Return every top-level field as a ``dict``, for splatting into a call.

    Sugar for ``select`` over the one-level names (``self.children``). On the
    batch and distribution subclasses, whose ``__getitem__`` returns a
    per-field view, the dict holds those views, so the result can be splatted
    back into a Function field-by-field.
    """
    return self.select(*self.children)

without(*paths)

Return a new Record without the fields and groups at paths.

The structural contract is NamedTree.without. Surviving fields keep their order and their authoritative specs; an untouched child is reused verbatim (class and metadata preserved), and a group a path reaches into is edited recursively. Dropping every leaf under a child prunes that child entirely.

Parameters:

Name Type Description Default
*paths str

One path per argument.

()

Returns:

Type Description
Record

The record without those nodes, under this record's label.

Raises:

Type Description
KeyError

If a path is not a path of this record.

TypeError

If a path is not a string, such as a tuple of paths.

ValueError

If a path is empty or has an empty name, the paths name a path twice or a path inside another, or every field would be removed.

Source code in probpipe/core/record.py
def without(self, *paths: str) -> Record:
    """Return a new Record without the fields and groups at *paths*.

    The structural contract is :meth:`NamedTree.without`. Surviving fields
    keep their order and their authoritative specs; an untouched child is
    reused verbatim (class and metadata preserved), and a group a path
    reaches into is edited recursively. Dropping every leaf under a child
    prunes that child entirely.

    Parameters
    ----------
    *paths : str
        One path per argument.

    Returns
    -------
    Record
        The record without those nodes, under this record's label.

    Raises
    ------
    KeyError
        If a path is not a path of this record.
    TypeError
        If a path is not a string, such as a tuple of paths.
    ValueError
        If a path is empty or has an empty name, the paths name a path
        twice or a path inside another, or every field would be removed.
    """
    paths = _as_path_arguments(paths, action="call without() with")
    for path in paths:
        self._existing_node_at(path)
    full_drops = {path for path in paths if _PATH_SEP not in path}
    sub_drops: dict[str, list[str]] = {}
    for path in paths:
        head, sep, rest = path.partition(_PATH_SEP)
        if sep:
            sub_drops.setdefault(head, []).append(rest)

    new_children: dict[str, Any] = {}
    specs: dict[str, Any] = {}
    for name, child in self._tree.items():
        if name in full_drops:
            continue
        drops = sub_drops.get(name)
        if drops is None:
            new_children[name] = child
            specs[name] = self._child_spec(name, child)
            continue
        # The path check above guarantees ``child`` is a group here.
        remaining = [
            k
            for k in child
            if not any(k == d or k.startswith(f"{d}{_PATH_SEP}") for d in drops)
        ]
        if not remaining:
            continue  # every leaf dropped -> prune the child entirely
        edited = child.without(*drops)
        new_children[name] = edited
        specs[name] = edited.event_template
    if not new_children:
        raise ValueError(
            f"without() cannot remove every field of {public_class_name(type(self))} "
            f"{self.label!r}"
        )
    return self._rebuild_root(new_children, RecordSpec(specs))

__and__(other)

Merge two records by top-level name: this record's fields and groups, then other's.

The merge is shallow, as NamedTree.__and__ states: a top-level name present in both records raises, even when the two groups hold different fields. Each child is reused as it is, with its class and metadata, and both records' specs are carried into the merged event_template.

Parameters:

Name Type Description Default
other Record

The record whose fields and groups are added.

required

Returns:

Type Description
Record

Both records' fields and groups side by side.

Raises:

Type Description
TypeError

If other is not a record, through NotImplemented.

ValueError

If a top-level name is in both records. Merge the groups first.

Examples:

>>> (Record({"a": 1.0}) & (Record({"b": 2.0, "g": {"c": 3.0}}))).keys()
('a', 'b', 'g/c')
Source code in probpipe/core/record.py
def __and__(self, other: Any) -> Record:
    """Merge two records by top-level name: this record's fields and groups, then *other*'s.

    The merge is shallow, as :meth:`NamedTree.__and__` states: a top-level
    name present in both records raises, even when the two groups hold
    different fields. Each child is reused as it is, with its class and
    metadata, and both records' specs are carried into the merged
    ``event_template``.

    Parameters
    ----------
    other : Record
        The record whose fields and groups are added.

    Returns
    -------
    Record
        Both records' fields and groups side by side.

    Raises
    ------
    TypeError
        If *other* is not a record, through ``NotImplemented``.
    ValueError
        If a top-level name is in both records. Merge the groups first.

    Examples
    --------
    >>> (Record({"a": 1.0}) & (Record({"b": 2.0, "g": {"c": 3.0}}))).keys()
    ('a', 'b', 'g/c')
    """
    if not isinstance(other, Record):
        return NotImplemented
    _check_no_shared_top_level_names(self, other, operands=f"the two {type(self).__name__}s")
    new_children: dict[str, Any] = {}
    specs: dict[str, Any] = {}
    for record, children in ((self, self._tree), (other, other._tree)):
        for name, child in children.items():
            new_children[name] = child
            specs[name] = record._child_spec(name, child)
    return self._rebuild_root(new_children, RecordSpec(specs))

replace(_updates=None, /, **updates)

Return a new Record with the values at the given paths replaced.

The structural contract is NamedTree.replace: every path must already exist, and a partial path replaces a whole subtree. Untouched fields keep their authoritative specs (untouched children are reused verbatim — class and metadata preserved); a replaced field takes its new value's inferred spec; a nested update edits the nested child recursively. Overlapping update paths (one an ancestor of another) raise ValueError.

Source code in probpipe/core/record.py
def replace(self, _updates: Mapping[str, Any] | None = None, /, **updates: Any) -> Record:
    """Return a new Record with the values at the given paths replaced.

    The structural contract is :meth:`NamedTree.replace`: every path must
    already exist, and a partial path replaces a whole subtree. Untouched
    fields keep their authoritative specs (untouched children are reused
    verbatim — class and metadata preserved); a replaced field takes its
    new value's inferred spec; a nested update edits the nested child
    recursively. Overlapping update paths (one an ancestor of another)
    raise ``ValueError``.
    """
    resolved = self._resolve_replace_updates(_updates, updates)
    if not resolved:
        return self
    full_updates = {path: value for path, value in resolved.items() if _PATH_SEP not in path}
    sub_updates: dict[str, dict[str, Any]] = {}
    for path, value in resolved.items():
        head, sep, rest = path.partition(_PATH_SEP)
        if sep:
            sub_updates.setdefault(head, {})[rest] = value

    new_children: dict[str, Any] = {}
    specs: dict[str, Any] = {}
    for name, child in self._tree.items():
        if name in full_updates:
            value = full_updates[name]
            new_children[name] = value
            specs[name] = self._spec_of(value)
        elif name in sub_updates:
            # The path check above guarantees ``child`` is a group.
            edited = child.replace(sub_updates[name])
            new_children[name] = edited
            specs[name] = edited.event_template
        else:
            new_children[name] = child
            specs[name] = self._child_spec(name, child)
    return self._rebuild_class()(
        new_children,
        event_template=RecordSpec(specs),
        label=self._label,
    )

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

Return a Record with the given nodes renamed or moved, old -> new.

The structural contract is NamedTree.rename: each key is the exact path of a node and each target its new exact path. The authoritative event_template is renamed by the same rule, so the subtree invariant holds on the result. The record keeps its label, since with_label relabels the record itself, and the result carries no provenance.

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 top-level node, keyed by the node's name.

{}

Returns:

Type Description
Record

A record over the same leaves at their new paths.

Raises:

Type Description
KeyError

If a key is not the path of a node.

TypeError

As NamedTree.rename raises it.

ValueError

As NamedTree.rename raises it.

Source code in probpipe/core/record.py
def rename(self, renames: Mapping[str, str] | None = None, /, **keyword_renames: str) -> Record:
    """Return a Record with the given nodes renamed or moved, ``old -> new``.

    The structural contract is :meth:`NamedTree.rename`: each key
    is the exact path of a node and each target its new exact path. The
    authoritative :attr:`event_template` is renamed by the same rule, so the
    subtree invariant holds on the result. The record keeps its label, since
    ``with_label`` relabels the record itself, and the result carries no
    provenance.

    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 top-level node, keyed by the node's name.

    Returns
    -------
    Record
        A record over the same leaves at their new paths.

    Raises
    ------
    KeyError
        If a key is not the path of a node.
    TypeError
        As :meth:`NamedTree.rename` raises it.
    ValueError
        As :meth:`NamedTree.rename` raises it.
    """
    resolved_renames = self._resolve_path_renames(renames, keyword_renames)
    tree, _ = self._renamed_tree(resolved_renames)
    return self._rebuild_root(tree, self.event_template.rename(resolved_renames))

to_dict()

Return a nested dict of stored values (leaves verbatim, no coercion).

Temporary: this is the same nested-tree export as to_nested_dict (the canonical name). It is retained during the migration and scheduled for removal; new code should call to_nested_dict. (The flat, path-keyed view is the builtin dict(record).)

Source code in probpipe/core/record.py
def to_dict(self) -> dict[str, Any]:
    """Return a nested ``dict`` of stored values (leaves verbatim, no coercion).

    Temporary: this is the same nested-tree export as :meth:`to_nested_dict`
    (the canonical name). It is retained during the migration and scheduled
    for removal; new code should call :meth:`to_nested_dict`. (The flat,
    path-keyed view is the builtin ``dict(record)``.)
    """
    return self.to_nested_dict()

to_numpy()

Return a dict of numpy arrays (recursive for nested Record).

Each numeric leaf is converted via np.asarray. Non-numeric leaves (strings, opaque objects) are returned as-is. Backend metadata (xarray dims / coords, pandas index) is stripped by this export — the record itself keeps its leaves in native form, so read the fields directly when you need the original containers.

Source code in probpipe/core/record.py
def to_numpy(self) -> dict[str, Any]:
    """Return a dict of numpy arrays (recursive for nested Record).

    Each numeric leaf is converted via ``np.asarray``. Non-numeric
    leaves (strings, opaque objects) are returned as-is. Backend
    metadata (xarray dims / coords, pandas index) is stripped by this
    export — the record itself keeps its leaves in native form, so
    read the fields directly when you need the original containers.
    """
    result: dict[str, Any] = {}
    for name, val in self._tree.items():
        if isinstance(val, Record):
            result[name] = val.to_numpy()
            continue
        backend = array_backend_for(val)
        if backend is not None:
            # A registered container (incl. non-numpy-protocol backends)
            # materialises through its own hook, not a raw ``np.asarray``
            # that would box the object.
            result[name] = backend.to_numpy(val)
        elif hasattr(val, "shape") or isinstance(val, (int, float, complex)):
            result[name] = np.asarray(val)
        else:
            result[name] = val
    return result

to_numeric()

Return this value as a NumericRecord, validating — not converting.

Every leaf must be numeric (a numeric scalar, a bare jax / numpy array, or a native container such as an xarray / pandas object). Leaves are stored in native form — nothing is coerced; conversion to jax.Array happens lazily at the compute boundary. Nested Record children recurse — every level becomes a NumericRecord. On a value that is already a NumericRecord this is the identity (returns self).

Returns:

Type Description
NumericRecord

A new record with this record's label and leaves, whose spec is inferred from the leaves.

Raises:

Type Description
TypeError

If any leaf is not numeric (e.g. strings, opaque Python objects).

Source code in probpipe/core/record.py
def to_numeric(self) -> NumericRecord:
    """Return this value as a :class:`NumericRecord`, validating — not converting.

    Every leaf must be numeric (a numeric scalar, a bare jax / numpy
    array, or a native container such as an ``xarray`` / ``pandas``
    object). Leaves are stored **in native form** — nothing is coerced;
    conversion to ``jax.Array`` happens lazily at the compute boundary.
    Nested ``Record`` children recurse — every level becomes a
    ``NumericRecord``. On a value that is already a ``NumericRecord``
    this is the identity (returns ``self``).

    Returns
    -------
    NumericRecord
        A new record with this record's label and leaves, whose spec is inferred
        from the leaves.

    Raises
    ------
    TypeError
        If any leaf is not numeric (e.g. strings, opaque Python
        objects).
    """
    # Lazy import to avoid the module-level circular dep:
    # _numeric_record.py imports Record from this module.
    from ._numeric_record import NumericRecord

    return NumericRecord(
        {
            field_name: val.to_numeric() if isinstance(val, Record) else val
            for field_name, val in self._tree.items()
        },
        label=self._label,
    )

from_fields(**fields) classmethod

Construct a record whose field names determine its label.

Parameters:

Name Type Description Default
**fields Any

Field values, including fields named label or name.

{}

Returns:

Type Description
Self

The record, promoted to its numeric kind when appropriate.

Raises:

Type Description
TypeError

If no fields are given, since the label is derived from them.

ValueError

If a field name contains /.

Source code in probpipe/core/record.py
@classmethod
def from_fields(cls, **fields: Any) -> Self:
    """Construct a record whose field names determine its label.

    Parameters
    ----------
    **fields : Any
        Field values, including fields named ``label`` or ``name``.

    Returns
    -------
    Self
        The record, promoted to its numeric kind when appropriate.

    Raises
    ------
    TypeError
        If no fields are given, since the label is derived from them.
    ValueError
        If a field name contains ``/``.
    """
    if not fields:
        raise TypeError(
            f"{cls.__name__}.from_fields() requires at least one field; "
            f"build an empty record with {cls.__name__}({{}}, label=...)"
        )
    for field_name in fields:
        _check_no_path_sep(field_name)
    return cls(fields)

ensure(x, *, label=None) classmethod

Coerce x to a record, returning a record unchanged.

  • a Record is returned as it is, and label is ignored;
  • a mapping becomes a record of its entries, and a nested mapping value becomes a nested record;
  • any other value becomes a record of one field, data, holding it.

Parameters:

Name Type Description Default
x Any

The value to coerce.

required
label str

The label of a newly built record. A record built from a mapping is labeled record(field,...) by default, from its top-level fields. A record wrapping a tracked term takes the term's label by default, and any other value has no default.

None

Returns:

Type Description
Record

x itself when it is a record of this class; otherwise a new record, promoted to NumericRecord when every field is numeric.

Raises:

Type Description
TypeError

If x is a value other than a mapping or a tracked term and label is omitted, or x is an empty mapping and label is omitted.

ValueError

If the fields of a mapping x are invalid, as the constructor states.

Source code in probpipe/core/record.py
@classmethod
def ensure(cls, x: Any, *, label: str | None = None) -> Record:
    """Coerce *x* to a record, returning a record unchanged.

    - a ``Record`` is returned as it is, and *label* is ignored;
    - a mapping becomes a record of its entries, and a nested mapping value
      becomes a nested record;
    - any other value becomes a record of one field, ``data``, holding it.

    Parameters
    ----------
    x : Any
        The value to coerce.
    label : str, optional
        The label of a newly built record. A record built from a mapping is
        labeled ``record(field,...)`` by default, from its top-level fields.
        A record wrapping a tracked term takes the term's label by default,
        and any other value has no default.

    Returns
    -------
    Record
        *x* itself when it is a record of this class; otherwise a new record,
        promoted to ``NumericRecord`` when every field is numeric.

    Raises
    ------
    TypeError
        If *x* is a value other than a mapping or a tracked term and *label*
        is omitted, or *x* is an empty mapping and *label* is omitted.
    ValueError
        If the fields of a mapping *x* are invalid, as the constructor
        states.
    """
    if isinstance(x, cls):
        return x
    if isinstance(x, Mapping):
        return cls(x, label=label)
    if label is None:
        if not isinstance(x, TrackedTerm):
            raise TypeError(
                f"{cls.__name__}.ensure() needs a label for a {type_name(x)}, which has none of its "
                f"own; pass label=..."
            )
        label = x.label
    return cls({"data": x}, label=label)

from_dict(fields, *, label=None) classmethod

Construct a record from a dict of field values.

It is the same as Record(fields, label=label), and remains as the dict-named spelling of that call.

Parameters:

Name Type Description Default
fields dict

The field values, keyed by field name.

required
label str or None

Keyword-only. The record's label; None, the default, derives record(field,...) from the top-level field names.

None

Returns:

Type Description
Record

The record, promoted to NumericRecord when every field is numeric.

Raises:

Type Description
TypeError

If label is omitted and fields is empty, or fields is a string, which is a label passed first in the earlier form.

ValueError

If a field name or value is invalid, as the constructor states.

Source code in probpipe/core/record.py
@classmethod
@refuses_label_first("fields")
def from_dict(
    cls, fields: dict[str, ArrayLike | Record], *, label: str | None = None
) -> Record:
    """Construct a record from a dict of field values.

    It is the same as ``Record(fields, label=label)``, and remains as the
    dict-named spelling of that call.

    Parameters
    ----------
    fields : dict
        The field values, keyed by field name.
    label : str or None
        Keyword-only. The record's label; ``None``, the default, derives
        ``record(field,...)`` from the top-level field names.

    Returns
    -------
    Record
        The record, promoted to ``NumericRecord`` when every field is
        numeric.

    Raises
    ------
    TypeError
        If *label* is omitted and *fields* is empty, or *fields* is a
        string, which is a label passed first in the earlier form.
    ValueError
        If a field name or value is invalid, as the constructor states.
    """
    return cls(fields, label=label)

from_field_values(template, values, *, label=None) classmethod

Reconstruct a value from an ordered sequence of field values.

values supplies one object per field, in canonical order (the order of the template's keys); the names and tree shape come from template, which the result carries as its authoritative event_template (nothing is inferred), so the round-trip is faithful: Record.from_field_values(r.event_template, r.values(), label=r.label) == r. The export side is just list(record.values()). The result's class follows the template's numericness — a NumericRecordSpec builds a NumericRecord via the auto-promotion.

Parameters:

Name Type Description Default
template RecordSpec

The authoritative schema supplying names, nesting, and order.

required
values iterable

One field value per template key, in canonical order.

required
label str or None

Keyword-only. The reconstructed record's label; None, the default, derives record(field,...) from the template's top-level fields.

None

Returns:

Type Description
Record

The reconstructed value (a NumericRecord for a numeric template).

Raises:

Type Description
TypeError

If label is omitted and template has no fields, or template is a string, which is a label passed first in the earlier form.

ValueError

If the number of values is not the number of fields (len(template)), or a value fails its field spec's structural is_valid at construction — a shape mismatch, or a cross-kind dtype (a NumericArraySpec's support is descriptive and not checked).

Source code in probpipe/core/record.py
@classmethod
@refuses_label_first("template", "values")
def from_field_values(
    cls, template: RecordSpec, values: Iterable[Any], *, label: str | None = None
) -> Record:
    """Reconstruct a value from an ordered sequence of field values.

    *values* supplies one object per field, in canonical order (the order
    of the template's :meth:`~NamedTree.keys`); the names and tree shape
    come from *template*, which the result carries as its
    **authoritative** :attr:`event_template` (nothing is inferred), so
    the round-trip is faithful:
    ``Record.from_field_values(r.event_template, r.values(), label=r.label) == r``.
    The export side is just ``list(record.values())``. The result's class
    follows the template's numericness — a :class:`NumericRecordSpec`
    builds a :class:`NumericRecord` via the auto-promotion.

    Parameters
    ----------
    template : RecordSpec
        The authoritative schema supplying names, nesting, and order.
    values : iterable
        One field value per template key, in canonical order.
    label : str or None
        Keyword-only. The reconstructed record's label; ``None``, the
        default, derives ``record(field,...)`` from the template's
        top-level fields.

    Returns
    -------
    Record
        The reconstructed value (a ``NumericRecord`` for a numeric
        template).

    Raises
    ------
    TypeError
        If *label* is omitted and *template* has no fields, or *template*
        is a string, which is a label passed first in the earlier form.
    ValueError
        If the number of *values* is not the number of fields
        (``len(template)``), or a value fails its field spec's structural
        ``is_valid`` at construction — a shape mismatch, or a cross-kind
        dtype (a ``NumericArraySpec``'s ``support`` is descriptive and not
        checked).
    """
    label = _derived_record_name(template.children) if label is None else label
    values = list(values)
    if len(values) != len(template):
        raise ValueError(
            f"Record.from_field_values: got {count(len(values), 'value')}, "
            f"expected {len(template)} (one per field)"
        )
    leaf_iter = iter(values)

    def _build(tpl: RecordSpec, node_name: str) -> Record:
        fields = {
            field_name: (
                _build(spec, field_name) if isinstance(spec, RecordSpec) else next(leaf_iter)
            )
            for field_name, spec in tpl.children.items()
        }
        # ``Record.__new__`` selects the class from the template.
        return Record(
            fields,
            event_template=tpl,
            label=node_name,
        )

    return _build(template, label)

__repr__()

The label, then the field paths in canonical order, read from the schema.

A numeric record shows its values below them.

Source code in probpipe/core/record.py
def __repr__(self) -> str:
    """The label, then the field paths in canonical order, read from the schema.

    A numeric record shows its values below them.
    """
    return self._repr_summary()

__eq__(other)

Two records are equal iff they have equal structure and equal data.

Concretely, equality requires (1) the same concrete type, (2) equal event_template (so two values with structurally distinct schemas — e.g. differing support on a numeric leaf — are unequal even with identical bytes), and (3) field-by-field equal values. A numeric leaf is compared on its native values (materialised through the array-backend registry — the same basis fingerprint uses, so equality and the content fingerprint agree) and on its native-container metadata (an xarray leaf's coords / dims / attrs, a pandas leaf's index / columns): two leaves with equal values but different coords are unequal, because that metadata is observable content. NaN positions compare equal (equal_nan), so a record with a NaN leaf equals an independent copy of itself. Nested records compare recursively; opaque leaves compare with ==.

Whether two records with equal data compare equal therefore turns on their templates. Built from equal data without an explicit template, both infer the same template and compare equal; but a record given a richer explicit template compares equal to a re-inferred rebuild of itself (e.g. via map) only when inference recovers that template, since RecordSpec.infer_from is lossy (it cannot recover a NumericArraySpec's dtype / support, etc.).

__hash__ is a coarser, structural hash (shape only, never the values or metadata), so equal records always hash equal while records that differ only in values or coords legitimately collide.

Source code in probpipe/core/record.py
def __eq__(self, other: object) -> bool:
    """Two records are equal iff they have equal structure **and** equal data.

    Concretely, equality requires (1) the same concrete type, (2) equal
    :attr:`event_template` (so two values with structurally distinct schemas
    — e.g. differing ``support`` on a numeric leaf — are unequal even with
    identical bytes), and (3) field-by-field equal values. A numeric leaf
    is compared on its **native values** (materialised through the
    array-backend registry — the same basis :func:`fingerprint` uses, so
    equality and the content fingerprint agree) **and** on its
    native-container metadata (an ``xarray`` leaf's coords / dims / attrs,
    a ``pandas`` leaf's index / columns): two leaves with equal values but
    different coords are unequal, because that metadata is observable
    content. ``NaN`` positions compare equal (``equal_nan``), so a record
    with a ``NaN`` leaf equals an independent copy of itself. Nested
    records compare recursively; opaque leaves compare with ``==``.

    Whether two records with equal data compare equal therefore turns on
    their templates. Built from equal data *without* an explicit template,
    both infer the same template and compare equal; but a record given a
    richer explicit template compares equal to a re-inferred rebuild of
    itself (e.g. via :meth:`map`) only when inference recovers that template,
    since :meth:`RecordSpec.infer_from` is lossy (it cannot recover a
    ``NumericArraySpec``'s ``dtype`` / ``support``, etc.).

    :meth:`__hash__` is a coarser, structural hash (shape only, never the
    values or metadata), so equal records always hash equal while records
    that differ only in values or coords legitimately collide.
    """
    # Identity fast-path — a cheap short-circuit before the field walk
    # (NaN leaves also compare equal across independent copies, via the
    # ``equal_nan`` comparison in ``_leaf_values_equal``).
    if self is other:
        return True
    if type(self) is not type(other):
        return NotImplemented
    if tuple(self._tree) != tuple(other._tree):
        return False
    if self.event_template != other.event_template:
        return False
    for name, a in self._tree.items():
        a, b = _leaf_value(a), _leaf_value(other._tree[name])
        if isinstance(a, Record) and isinstance(b, Record):
            if a != b:
                return False
        elif isinstance(a, Record) or isinstance(b, Record):
            return False
        elif (
            _full_array_shape_or_none(a) is not None or _full_array_shape_or_none(b) is not None
        ):
            # A numeric leaf (native container or bare array): compare the
            # native values (the fingerprint basis), then the
            # native-container metadata (coords / index / ...).
            try:
                if not _leaf_values_equal(a, b):
                    return False
            except Exception:
                if a is not b and a != b:
                    return False
                continue
            if _leaf_metadata_key(a) != _leaf_metadata_key(b):
                return False
        else:
            if a != b:
                return False
    return True

NumericRecord(fields, /, *, label=None, event_template=None, _validate_leaves=True)

Bases: Record, Numeric

A Record whose fields are all numeric, stored in native form.

A NumericRecord is the numeric specialization of Record. It holds the same named, ordered, possibly-nested collection of fields, but constrains every field to be numeric. It inherits the full Record interface — the leaf-keyed mapping, the tree navigation, the metadata (label, provenance), and the equality and hashing rules — and adds the array-only features described below.

The numeric-leaf invariant, and native storage. Every field must be numeric — a numeric array or container from any supported backend (jax.numpy, numpy, xarray.DataArray, a pandas object with numeric dtypes, or any type registered via register_array_backend), or a numeric Python scalar (int, float, complex, or bool); interior nodes are themselves NumericRecord instances. Construction validates without converting: an array-like leaf is stored verbatim in its native form, reading only its container metadata (shape / dtype), so a lazy or disk-backed value is not materialised. A bare Python scalar — which carries no metadata — is normalised to a 0-d jax.Array. Any non-numeric leaf raises TypeError at construction, naming the offending field.

Lazy conversion at the compute boundary. Navigation returns native leaves verbatim: record["x"], children, and at_path never convert. Conversion to jax.Array happens at the compute boundary — the JAX pytree flatten that jit / vmap / grad traverse, to_vector, and the single-field scalar shim — through a per-leaf cache. Concrete conversions are memoised per record instance; traced conversions stay within their transform. A JAX transform returns a record with bare jax.Array leaves (unflatten cannot rebuild native containers); structural transforms (without / merge / replace / rename) and pickling reuse the native leaves verbatim, so native types survive them.

Aliasing and mutation. Native leaves are stored by reference, exactly as a plain Record stores opaque leaves, and construction marks a NumPy array leaf read-only in place, so a write through the caller's handle or through raw raises ValueError. A pandas or xarray container carries no such flag, so mutating it in place after construction changes the record. Once that leaf has crossed a compute boundary, navigation and compute can disagree: navigation reflects the mutation, but compute reuses the jax.Array snapshot cached at the first concrete conversion. Records assume their containers are not externally mutated mid-pipeline; no defensive copies are made.

Equality, hashing, and lazy leaves. __eq__ and content fingerprints compare converted values (and native-container metadata such as coords / index), so computing them on a record with lazy / disk-backed leaves forces materialisation on demand. __hash__ is a coarser structural hash over shape and dtype only — it reads container metadata, never the values, so hashing a lazy leaf does not materialise it (records differing only in values or coords hash equal, a legal collision).

The flat vector form. Because every leaf is numeric, the record implements Numeric, and the whole value can be flattened into a single dense 1-D array. to_vector converts and ravels the leaves, in canonical order, into a vector of length vector_size; from_vector rebuilds the record from such a vector (with bare jax.Array leaves). Note that this is different from list(record.values()), which returns the ordered list of native fields and is supported by any Record.

Truth depends on the number of top-level fields, as for any record: an empty record is false and every nonempty record is true.

Single-field records as scalars. A NumericRecord with exactly one field behaves like a thin wrapper around that field's value: float(r), int(r), np.asarray(r), jnp.asarray(r), and the r.shape / r.dtype / r.ndim attributes all forward to the sole leaf (only the value coercions materialise it). A record with more than one field, or whose single child is a nested record — an interior node, not a field — raises TypeError from these conversions, since unwrapping one field of several would be ambiguous; access a specific field explicitly in that case. The array conversions override the ones Numeric supplies, which present to_vector. The override is an interim implementation detail until a record no longer presents a single field.

Parameters:

Name Type Description Default
fields Mapping

Field values in canonical first-appearance order. A mapping value becomes a nested record. Slash-delimited keys declare nested paths. Fields named label, name, and event_template remain ordinary mapping keys.

required
label str

The root's display alias. Defaults to record(field,...) from the declared top-level fields. An empty record requires an explicit label.

None
event_template NumericRecordSpec

The authoritative schema. Defaults to the schema inferred from the fields. A supplied schema is validated and its shared dimensions are bound jointly.

None
_validate_leaves bool

Whether to validate leaves against a supplied template. Internal numerical reconstruction skips this check. Numeric records still require numeric leaves.

True

Raises:

Type Description
TypeError

If any leaf is not a numeric array or container, a numeric scalar, or a nested NumericRecord; or for any reason Record states: a fields that is not a mapping, a string given where the fields go with label omitted, or no fields with label omitted.

ValueError

If the field paths conflict or a supplied event_template disagrees with the fields or their values, as for Record.

Notes

Constructing NumericRecord(fields, label=label), constructing Record(fields, label=label) from all-numeric fields (which auto-promotes), and calling to_numeric() follow the same validation path and produce identical results; to_numeric() on an existing NumericRecord is the identity.

The compute boundary presents a plain PyTree of arrays: the JAX pytree children are the converted leaves, so jit / vmap / grad see exactly the ProbPipe structure. As on Record, the PyTree aux carries the (spec, label) pair, so the declared type and the label survive a flatten/unflatten round-trip; provenance, annotations, and the native container types do not cross a JAX transform boundary.

Source code in probpipe/core/_numeric_record.py
def __init__(
    self,
    fields: Mapping[str, Any],
    /,
    *,
    label: str | None = None,
    event_template: RecordSpec | None = None,
    _validate_leaves: bool = True,
):
    if not isinstance(fields, Mapping):
        raise TypeError(_not_a_field_mapping(type(self).__name__, fields))
    raw_inputs = _unflatten_paths(fields)
    # Materialise structural nesting (path-keyed construction) into nested
    # NumericRecords *before* leaf validation, so the numeric check happens
    # on the nested record that owns each leaf.
    raw_fields: dict[str, Any] = {}
    for field_name, value in raw_inputs.items():
        if isinstance(value, Mapping):
            # A mapping value is nested structure: materialise the child.
            sub_template: RecordSpec | None = None
            if event_template is not None:
                child = event_template.children.get(field_name)
                if isinstance(child, RecordSpec):
                    sub_template = child
            raw_fields[field_name] = type(self)(
                value,
                event_template=sub_template,
                label=field_name,
            )
        else:
            raw_fields[field_name] = value
    validated = self._validate(raw_fields)
    super().__init__(
        validated,
        event_template=event_template,
        _validate_leaves=_validate_leaves,
        label=label,
    )
    # Cache vector_size, reading only container metadata (shapes) — a
    # lazy / disk-backed leaf is not materialised here.
    total = 0
    for val in self._tree.values():
        if isinstance(val, NumericRecord):
            total += val.vector_size
        else:
            total += int(prod(_event_shape_of(val)))
    object.__setattr__(self, "_vector_size", total)
    # The set-once converted-leaf cache backing the compute boundary.
    # Mutable by design (an internal memo, not value state); shallow
    # copies share it, so a conversion benefits every identity copy.
    object.__setattr__(self, "_jax_cache", {})

vector_size property

Length of this record's 1-D vector (to_vector / from_vector).

The total number of scalar elements across all numeric leaves — the length of to_vector's output. Computed from container metadata at construction; no values are materialised.

dtype property

The sole leaf's dtype, or None when it has no single dtype.

A registered backend reports the leaf's dtype (None for a heterogeneous container such as a mixed-column frame); a bare array-like forwards its own .dtype. A leaf that exposes no single dtype yields None rather than a stand-in.

to_vector()

Serialize to the dense 1-D vector of shape (vector_size,).

The numeric 1-D serialization: the record's numeric leaves, visited in canonical leaf order (keys — insertion order, depth-first into nested records), each converted to jax.Array at the compute boundary, raveled, and concatenated into one dense vector. Concrete leaf conversions are memoised. The inverse is from_vector.

This is distinct from list(record.values()), which keeps each leaf whole and native (any type); to_vector ravels and concatenates the numeric leaves into a single dense vector.

Source code in probpipe/core/_numeric_record.py
def to_vector(self) -> jnp.ndarray:
    """Serialize to the dense 1-D vector of shape ``(vector_size,)``.

    The numeric 1-D serialization: the record's numeric leaves, visited in
    canonical leaf order (:meth:`~probpipe.core.named_tree.NamedTree.keys` —
    insertion order, depth-first into nested records), each converted to
    ``jax.Array`` at the compute boundary, raveled, and concatenated into
    one dense vector. Concrete leaf conversions are memoised. The inverse is
    :meth:`from_vector`.

    This is distinct from ``list(record.values())``, which keeps each leaf
    whole and native (any type); ``to_vector`` ravels and concatenates the
    numeric leaves into a single dense vector.
    """
    leaves = [self._field_as_jax(key) for key in self.event_template]
    if not leaves:
        # ``jnp.concatenate`` refuses an empty list; a record with no
        # numeric leaves has ``vector_size == 0`` and serialises to the
        # zero-length vector, which concatenates as the identity.
        return jnp.zeros(0)
    return jnp.concatenate([jnp.reshape(leaf, -1) for leaf in leaves])

from_vector(spec, vec, *, label=None) classmethod

Reconstruct a single record from its dense 1-D vector.

The value-level inverse of to_vector: splits vec into the spec's per-field blocks, reshapes each to its NumericArraySpec shape in canonical leaf order, and returns a NumericRecord carrying spec as its authoritative schema under label. The reconstructed leaves are bare jax.Array\ s — a flat vector carries no native container to restore.

Parameters:

Name Type Description Default
spec NumericRecordSpec

The flat layout supplying field names, shapes, and order. Every leaf must be a NumericArraySpec.

required
vec Array

A vector of shape (spec.vector_size,) — one single (unbatched) value.

required
label str or None

Keyword-only. The reconstructed record's label; None, the default, derives record(field,...) from the spec's top-level fields, as the constructor does.

None

Returns:

Type Description
NumericRecord

The reconstructed record, with record.to_vector() equal to vec.

Raises:

Type Description
TypeError

If spec contains a non-array leaf; if vec carries leading batch axes — batched reconstruction is the batch type's concern; use NumericRecordBatch.from_vector for a batched matrix; if label is omitted and spec has no fields to derive it from; or if spec is a string, which is a label passed first in the earlier form.

ValueError

If the vector length does not equal spec.vector_size.

Source code in probpipe/core/_numeric_record.py
@classmethod
@refuses_label_first("spec", "vec")
def from_vector(
    cls, spec: NumericRecordSpec, vec: Array, *, label: str | None = None
) -> NumericRecord:
    """Reconstruct a single record from its dense 1-D vector.

    The value-level inverse of :meth:`to_vector`: splits *vec* into the
    spec's per-field blocks, reshapes each to its ``NumericArraySpec`` shape
    in canonical leaf order, and returns a ``NumericRecord`` carrying
    *spec* as its authoritative schema under *label*.
    The reconstructed leaves are bare ``jax.Array``\\ s — a flat vector
    carries no native container to restore.

    Parameters
    ----------
    spec : NumericRecordSpec
        The flat layout supplying field names, shapes, and order. Every
        leaf must be a NumericArraySpec.
    vec : Array
        A vector of shape ``(spec.vector_size,)`` — one single
        (unbatched) value.
    label : str or None
        Keyword-only. The reconstructed record's label; ``None``, the
        default, derives ``record(field,...)`` from the spec's top-level
        fields, as the constructor does.

    Returns
    -------
    NumericRecord
        The reconstructed record, with ``record.to_vector()`` equal to
        *vec*.

    Raises
    ------
    TypeError
        If *spec* contains a non-array leaf; if *vec* carries
        leading batch axes — batched reconstruction is
        the batch type's concern; use :meth:`NumericRecordBatch.from_vector`
        for a batched matrix; if *label* is omitted and *spec* has no
        fields to derive it from; or if *spec* is a string, which is a
        label passed first in the earlier form.
    ValueError
        If the vector length does not equal ``spec.vector_size``.
    """
    vec = jnp.asarray(vec)
    if vec.ndim != 1:
        raise TypeError(
            f"NumericRecord.from_vector expects a 1-D vector (one value); "
            f"got shape {tuple(vec.shape)}. Reconstruct a batch with "
            f"NumericRecordBatch.from_vector."
        )
    label = _derived_record_name(spec.children) if label is None else label
    return _reconstruct_from_vector(label, spec, vec)

to_numeric()

Return self — a NumericRecord is already numeric (identity).

Source code in probpipe/core/_numeric_record.py
def to_numeric(self) -> NumericRecord:
    """Return ``self`` — a ``NumericRecord`` is already numeric (identity)."""
    return self

__repr__()

The class and the label, then one line for each field with its path and its value.

A nested path reads population/mu. NumPy's printing formats each value, so np.set_printoptions sets the precision and shortens a large array with ..., and a shortened value ends with its shape. Only the entries shown are read from the device. Inside a JAX trace, where the values are tracers, and for a record with no fields, the repr is the summary of the label and the field paths.

A record of summaries displays as a table under its label instead. Its top-level fields are records over the same paths, with the same shape at each path, and at least one of them records how it was computed, as the term an operation returns does. The table has one row for each path, or for each element of an array path, as y[0], and one column for each top-level field, and its lines are indented by two spaces, as a record's lines are. The line below the table states how each column was computed: exact, Monte Carlo with the number of draws, or approximate.

Source code in probpipe/core/_numeric_record.py
def __repr__(self) -> str:
    """The class and the label, then one line for each field with its path and its value.

    A nested path reads ``population/mu``. NumPy's printing formats each
    value, so ``np.set_printoptions`` sets the precision and shortens a large
    array with ``...``, and a shortened value ends with its shape. Only the
    entries shown are read from the device. Inside a JAX trace, where the
    values are tracers, and for a record with no fields, the repr is the
    summary of the label and the field paths.

    A record of summaries displays as a table under its label instead. Its
    top-level fields are records over the same paths, with the same shape
    at each path, and at least one of them records how it was computed, as
    the term an operation returns does. The table has one row for each
    path, or for each element of an array path, as ``y[0]``, and one column
    for each top-level field, and its lines are indented by two spaces, as a
    record's lines are. The line below the table states how each column
    was computed: ``exact``, ``Monte Carlo`` with the number of draws, or
    ``approximate``.
    """
    table = record_table(self)
    if table is not None:
        lines = table.lines(VALUE_INDENT)
        return "\n".join([self._displayed_label(), *lines, table.footer])
    return summary_with_values(
        self._repr_summary(structure=False),
        format_rows(self._value_rows(), VALUE_INDENT),
        alone=self._repr_summary(),
    )

__str__()

The lines of the repr's values alone, one for each field with its path and its value.

A record that displays as a table gives the table without its label and the line below it. Inside a JAX trace, and for a record with no fields, str() is the summary of the label and the field paths.

Source code in probpipe/core/_numeric_record.py
def __str__(self) -> str:
    """The lines of the repr's values alone, one for each field with its path and its value.

    A record that displays as a table gives the table without its label and
    the line below it. Inside a JAX trace, and for a record with no fields,
    ``str()`` is the summary of the label and the field paths.
    """
    table = record_table(self)
    if table is not None:
        return "\n".join(table.lines())
    rows = format_rows(self._value_rows())
    return self._repr_summary() if rows is None else rows

__bool__()

Whether this record holds any field, at any depth, whatever its values.

A record whose only top-level name is an empty group holds no field, so it is false, as its length of 0 says.

Source code in probpipe/core/_numeric_record.py
def __bool__(self) -> bool:
    """Whether this record holds any field, at any depth, whatever its values.

    A record whose only top-level name is an empty group holds no field, so
    it is false, as its length of 0 says.
    """
    return len(self) != 0

Numeric arrays

NumericArray(value, /, *, label, spec=None, provenance=None)

Bases: TrackedTerm, Annotated, Numeric

One numeric array value, with identity.

The tracked class of the numeric-array kind, as Record is of the record kind: what an operation returns when its declared kind is a NumericArraySpec. It holds a single array and carries no batch axes, so shape is the event shape; multiplicity lives in NumericArrayBatch.

Parameters:

Name Type Description Default
value array - like

The array this term holds, stored verbatim in its native form: a bare array, an xarray / pandas container, or any registered backend, so a lazy or disk-backed value stays lazy. Python numeric scalars, including subclasses, are normalised to a 0-d jax.Array; NumPy scalars retain their native form and dtype. A NumPy array is marked read-only in place, so a write through the caller's handle or through raw raises ValueError.

required
label str

The value's required semantic name. A value carries no fields to describe it, so the label is what says which one it is; a class-name default would label every array in a pipeline alike.

required
spec NumericArraySpec

What this value satisfies. Derived from the array's shape and dtype when omitted, with an unconstrained support.

None
provenance Provenance

How this value was produced.

None

Raises:

Type Description
TypeError

If spec is not a NumericArraySpec, or if value is not a numeric leaf.

ValueError

If value's shape or dtype does not satisfy spec.

Notes

Construction validates native arrays and NumPy scalars against metadata alone, deferring JAX conversion to as_jax. NumPy scalars retain their original precision in raw and np.asarray(value). JAX conversion follows its x64 configuration and can round or overflow; float(value) also goes through as_jax.

It carries the full array surface: arithmetic, comparison, and the conversion hooks. With one value and no fields, arr + 1 has a single meaning, which is what lets Record stay a container. It implements Numeric: its vector is the array raveled in row-major order, and its conversion hooks present the array itself rather than that vector, so NumPy and JAX functions see its shape and return bare arrays.

An operator returns a NumericArray holding the stored value's result, labeled by the expression in evaluation order, such as draw + 1, with its tracked operands as the provenance's parents. A term presents as its raw representation inside a JAX trace, so there an operator returns the bare result. Indexing and iteration return the stored value's entries and rows.

As a JAX pytree it flattens to its array, with its spec as the static data. The label and the expression do not cross a transform, so two values that differ only in their labels have equal treedefs and share a compilation, and a value rebuilt from its leaves is labeled <no description> until a result boundary labels it.

Examples:

>>> import jax.numpy as jnp
>>> value = NumericArray(
...     jnp.arange(3.0),
...     label="draw",
... )
>>> value.shape
(3,)
>>> value + 1
NumericArray('draw + 1', shape=(3,), dtype=float32)
  [1. 2. 3.]
Source code in probpipe/core/_numeric_array.py
def __init__(
    self,
    value: Any,
    /,
    *,
    label: str,
    spec: NumericArraySpec | None = None,
    provenance: Provenance | None = None,
) -> None:
    if spec is not None and not isinstance(spec, NumericArraySpec):
        raise TypeError(
            f"NumericArray spec must be a NumericArraySpec, got {type(spec).__name__}"
        )
    if not _is_numeric_leaf(value):
        raise TypeError(
            _not_numeric("NumericArray", "value", value, what="a numeric array or scalar")
        )
    stored = _stored(value)
    if spec is None:
        spec = _inferred_spec(stored)
    elif not spec.is_valid(stored):
        raise ValueError(
            f"NumericArray {label!r}: value of shape {_event_shape_of(stored)} and dtype "
            f"{_numpy_dtype_of(stored)} does not match spec {spec}"
        )
    object.__setattr__(self, "_value", _read_only(stored))
    object.__setattr__(self, "_spec", spec)
    self._init_tracked(label, provenance=provenance)

raw property

The stored array, in the form it was given. Untracked.

spec property

This value's own declaration.

shape property

The event shape, read from the value's metadata. No batch axes.

dtype property

The stored value's dtype, or None when it has no single one.

The value's rather than the declaration's, as for a single-field NumericRecord: a caller sizing a buffer or branching on the dtype is asking about the data. The two can differ, since is_valid admits a same-kind cast; spec carries the declaration.

vector_size property

Length of this array's 1-D vector, the number of its elements.

as_jax()

The value as a jax.Array — the single conversion point.

A value already stored as one passes through, tracers included; a native container converts through its registered backend. Concrete conversions are memoised; traced conversions stay within their transform.

Conversion follows JAX's x64 configuration, so a stored float64 can become float32 and round or overflow when x64 is disabled. Enable x64 before the first conversion when float64 is required; an existing concrete cache is reused even if that configuration later changes.

Source code in probpipe/core/_numeric_array.py
def as_jax(self) -> Any:
    """The value as a ``jax.Array`` — the single conversion point.

    A value already stored as one passes through, tracers included; a
    native container converts through its registered backend. Concrete
    conversions are memoised; traced conversions stay within their transform.

    Conversion follows JAX's x64 configuration, so a stored float64 can
    become float32 and round or overflow when x64 is disabled. Enable x64
    before the first conversion when float64 is required; an existing
    concrete cache is reused even if that configuration later changes.
    """
    if isinstance(self._value, jax.Array):
        return self._value
    cached = getattr(self, "_jax_cache", None)
    if cached is None:
        cached = _to_jax_array(self._value)
        if not isinstance(cached, jax.core.Tracer):
            object.__setattr__(self, "_jax_cache", cached)
    return cached

to_vector()

Serialize to the dense 1-D vector of shape (vector_size,), in row-major order.

The value converts to jax.Array at the compute boundary, as as_jax does. The inverse is from_vector.

Source code in probpipe/core/_numeric_array.py
def to_vector(self) -> jax.Array:
    """Serialize to the dense 1-D vector of shape ``(vector_size,)``, in row-major order.

    The value converts to ``jax.Array`` at the compute boundary, as
    :meth:`as_jax` does. The inverse is :meth:`from_vector`.
    """
    return jnp.reshape(self.as_jax(), -1)

from_vector(spec, vec, *, label) classmethod

Reconstruct a single array from its dense 1-D vector.

The value-level inverse of to_vector: reshapes vec to the shape spec declares, casts it to the declared dtype when there is one, and returns a NumericArray carrying spec under label. The rebuilt value is a bare jax.Array, since a flat vector carries no native container to restore.

Parameters:

Name Type Description Default
spec NumericArraySpec

The declaration supplying the shape and dtype, with every dimension bound.

required
vec Array

A vector of shape (spec.vector_size,), one unbatched value.

required
label str

Keyword-only and required, with no default, since a raw array's data cannot identify the value.

required

Returns:

Type Description
NumericArray

The reconstructed array, whose to_vector() equals vec.

Raises:

Type Description
TypeError

If vec is not one-dimensional, since a batch of vectors belongs to NumericArrayBatch; if label is omitted; or if spec is a string, which is a label passed first in the earlier form.

ValueError

If spec has unbound dimensions, or the vector's length is not spec.vector_size.

Source code in probpipe/core/_numeric_array.py
@classmethod
@refuses_label_first("spec", "vec")
def from_vector(cls, spec: NumericArraySpec, vec: Any, *, label: str) -> NumericArray:
    """Reconstruct a single array from its dense 1-D vector.

    The value-level inverse of :meth:`to_vector`: reshapes *vec* to the shape
    *spec* declares, casts it to the declared dtype when there is one, and
    returns a ``NumericArray`` carrying *spec* under *label*. The rebuilt
    value is a bare ``jax.Array``, since a flat vector carries no native
    container to restore.

    Parameters
    ----------
    spec : NumericArraySpec
        The declaration supplying the shape and dtype, with every dimension
        bound.
    vec : Array
        A vector of shape ``(spec.vector_size,)``, one unbatched value.
    label : str
        Keyword-only and required, with no default, since a raw array's data
        cannot identify the value.

    Returns
    -------
    NumericArray
        The reconstructed array, whose ``to_vector()`` equals *vec*.

    Raises
    ------
    TypeError
        If *vec* is not one-dimensional, since a batch of vectors belongs to
        :class:`~probpipe.NumericArrayBatch`; if *label* is omitted; or if
        *spec* is a string, which is a label passed first in the earlier
        form.
    ValueError
        If *spec* has unbound dimensions, or the vector's length is not
        ``spec.vector_size``.
    """
    vec = jnp.asarray(vec)
    if vec.ndim != 1:
        raise TypeError(
            f"NumericArray.from_vector expects a 1-D vector (one value); "
            f"got shape {tuple(vec.shape)}"
        )
    if vec.shape[0] != spec.vector_size:
        raise ValueError(
            f"NumericArray.from_vector: the vector has length {vec.shape[0]}, "
            f"expected vector_size={spec.vector_size}"
        )
    value = jnp.reshape(vec, spec.shape)
    if spec.dtype is not None:
        value = value.astype(spec.dtype)
    return cls(
        value,
        spec=spec,
        label=label,
    )

__str__()

The stored value's entries as NumPy prints them, as print shows the array.

Inside a JAX trace, where the value is a tracer, str() is the repr's summary.

Source code in probpipe/core/_numeric_array.py
def __str__(self) -> str:
    """The stored value's entries as NumPy prints them, as ``print`` shows the array.

    Inside a JAX trace, where the value is a tracer, ``str()`` is the
    repr's summary.
    """
    values = format_entries(self._value)
    return self._repr_summary() if values is None else values

__format__(format_spec)

The stored value formatted by format_spec, as f"{x:.2f}" formats a scalar.

Source code in probpipe/core/_numeric_array.py
def __format__(self, format_spec: str) -> str:
    """The stored value formatted by *format_spec*, as ``f"{x:.2f}"`` formats a scalar."""
    return format(self._value, format_spec)

__repr__()

A summary of the label, the shape, the dtype, and any support, then the entries below it.

Each line of the entries is indented by two spaces, as a record's lines are. NumPy's printing formats the entries, so np.set_printoptions sets their precision and shortens a large array with ..., and only the entries shown are read from the device. Inside a JAX trace, where the value is a tracer, the repr is the summary alone.

Source code in probpipe/core/_numeric_array.py
def __repr__(self) -> str:
    """A summary of the label, the shape, the dtype, and any support, then the entries below it.

    Each line of the entries is indented by two spaces, as a record's lines
    are. NumPy's printing formats the entries, so ``np.set_printoptions`` sets
    their precision and shortens a large array with ``...``, and only the
    entries shown are read from the device. Inside a JAX trace, where the
    value is a tracer, the repr is the summary alone.
    """
    return summary_with_values(self._repr_summary(), format_entries(self._value, VALUE_INDENT))

Numeric

Bases: ABC

The flat-vector interface of the numeric kinds.

NumericArray and NumericRecord implement it.

A numeric value lays itself out as one flat vector in canonical order. to_vector returns that vector, vector_size is its length, and from_vector rebuilds a value from one. The base supplies the coordinate protocols, which present the vector to NumPy and JAX, so their functions return bare arrays. A batch form is not Numeric, since its elements are the numeric values.

Notes

NumericArray restates the coordinate protocols to present its array itself, whose row-major order is its vector's. NumericRecord restates them to present its sole field, an interim implementation detail until a record no longer presents a single field.

vector_size abstractmethod property

The length of this value's flat vector.

to_vector() abstractmethod

This value's coordinates, one flat vector in canonical order.

Source code in probpipe/core/_numeric.py
@abstractmethod
def to_vector(self) -> jax.Array:
    """This value's coordinates, one flat vector in canonical order."""

from_vector(spec, vec, *, label) abstractmethod classmethod

Rebuild the value that spec declares from its flat vector vec.

It inverts to_vector. Every numeric kind takes label, so a caller that holds only a Numeric class passes it. A kind may also derive a default, as NumericRecord.from_vector <probpipe.NumericRecord.from_vector> derives one from the record's top-level fields.

Parameters:

Name Type Description Default
spec NumericSpec

The declaration of the value, which supplies its layout.

required
vec Any

The flat vector, of length spec.vector_size.

required
label str

Keyword-only. The label of the rebuilt value.

required

Returns:

Type Description
Self

The value whose to_vector equals vec.

Source code in probpipe/core/_numeric.py
@classmethod
@abstractmethod
def from_vector(cls, spec: NumericSpec, vec: Any, *, label: str) -> Self:
    """Rebuild the value that *spec* declares from its flat vector *vec*.

    It inverts :meth:`to_vector`. Every numeric kind takes *label*, so a
    caller that holds only a ``Numeric`` class passes it. A kind may also
    derive a default, as :meth:`NumericRecord.from_vector
    <probpipe.NumericRecord.from_vector>` derives one from the record's
    top-level fields.

    Parameters
    ----------
    spec : NumericSpec
        The declaration of the value, which supplies its layout.
    vec : Any
        The flat vector, of length ``spec.vector_size``.
    label : str
        Keyword-only. The label of the rebuilt value.

    Returns
    -------
    Self
        The value whose :meth:`to_vector` equals *vec*.
    """

Opaque values

Opaque(value, /, *, label, spec=None, provenance=None)

Bases: TrackedTerm, Annotated

One value of no exposed structure, with identity.

The tracked class of the opaque kind, as Record is of the record kind: what an operation returns when its declared kind is an OpaqueSpec. Its batch form is OpaqueBatch.

Its interface is raw plus the identity every tracked term carries. What the value affords is its own type's, once it is out.

Parameters:

Name Type Description Default
value Any

The value this term holds, stored as given. Any non-mapping value; the value layer reads a mapping as a subtree. A NumPy array is marked read-only in place.

required
label str

The required semantic description, passed by keyword: an opaque value has no fields or callable name from which to derive one.

required
spec OpaqueSpec

What this value satisfies, carrying any opaque meta. Defaults to the OpaqueSpec of the value's type.

None
provenance Provenance

How this value was produced.

None

Raises:

Type Description
TypeError

If spec is not an OpaqueSpec, or if value is a mapping.

Examples:

>>> fitted = Opaque(
...     object(),
...     label="sklearn_model",
... )
>>> fitted.label
'sklearn_model'
Source code in probpipe/core/_opaque.py
def __init__(
    self,
    value: Any,
    /,
    *,
    label: str,
    spec: OpaqueSpec | None = None,
    provenance: Provenance | None = None,
) -> None:
    if spec is not None and not isinstance(spec, OpaqueSpec):
        raise TypeError(f"Opaque spec must be an OpaqueSpec, got {type(spec).__name__}")
    if isinstance(value, Mapping):
        raise TypeError(
            f"Opaque cannot hold a mapping, got {type_name(value)}; use a Record for "
            f"structured values"
        )
    if spec is None:
        spec = OpaqueSpec(type=type(value))
    elif not spec.is_valid(value):
        raise TypeError(
            f"Opaque {label!r}: value of type {type_name(value)} does not match {spec!r}"
        )
    object.__setattr__(self, "_value", _read_only(value))
    object.__setattr__(self, "_spec", spec)
    self._init_tracked(label, provenance=provenance)

raw property

The wrapped value. Untracked.

spec property

This value's own declaration.

__repr__()

The label, then the declared type and the metadata where the spec sets them.

Source code in probpipe/core/_opaque.py
def __repr__(self) -> str:
    """The label, then the declared type and the metadata where the spec sets them."""
    return term_repr("Opaque", self._displayed_label(), self._spec._repr_arguments())

__str__()

The wrapped value's string, as print and an f-string show the value.

Source code in probpipe/core/_opaque.py
def __str__(self) -> str:
    """The wrapped value's string, as ``print`` and an f-string show the value."""
    return str(self._value)

__format__(format_spec)

The wrapped value formatted by format_spec.

Source code in probpipe/core/_opaque.py
def __format__(self, format_spec: str) -> str:
    """The wrapped value formatted by *format_spec*."""
    return format(self._value, format_spec)

Batches

Batch

Bases: TrackedTerm, ABC

A tracked nd collection of elements of a common type.

The batch axes are grouped into named levels, and indexing them returns a view — an element once the selection reaches one, a sub-batch otherwise — whose label records what it selected. Index by position with [], by level name with at_levels, and, where the elements have fields, by field name with [] as well; len and iter walk the leading axis.

A concrete subclass supplies the element storage, calling _init_batch from its constructor; this class stores the batch's BatchSpec and the identity TrackedTerm provides, and nothing else.

Attributes:

Name Type Description
spec BatchSpec

This batch's own specification, at the family kind. The single stored source of its type: everything below is a view on it.

element_spec OutputSpec

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

batch_shape tuple of int

The batch axes, the flat concatenation of axis_groups. Always non-empty: a batch has at least one batch axis.

batch_size int

The total element count, prod(batch_shape).

axis_groups tuple of tuple of int

batch_shape tiled into levels, outermost level first.

level_names tuple of str

One name per level, aligned with axis_groups, unique within the batch.

Notes

batch_shape and batch_size are named rather than reusing numpy's shape / size because a bare name would ambiguously cover both the batch axes and the content of one element.

A batch is immutable, by Immutable: assignment and deletion raise, and pickle / copy restore its state around that guard.

spec property

This batch's own specification, at the family kind.

element_spec property

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

A view on spec. A batch built from bare values takes the raw default, which names single arrays or opaque values "element".

batch_shape property

The batch axes, flat: the concatenation of axis_groups.

batch_size property

The total element count, prod(batch_shape).

axis_groups property

batch_shape tiled into levels, outermost level first.

level_names property

One name per level, aligned with axis_groups.

with_level_names(mapping=None, /, **kwargs)

Rename levels old -> new; shapes and elements are unchanged.

Accepts a positional mapping, keyword pairs, or both. Every name given must be a level of this batch, and the result must still name each level once.

Parameters:

Name Type Description Default
mapping Mapping of str to str

Renames as {old: new}, positional so that any level name is addressable even where it is not a valid keyword.

None
**kwargs str

Renames as old="new", for the common case. A level named in both must be given the same new name in each.

{}

Returns:

Type Description
Self

A shallow copy over the same axes and elements, specified over the new level names, preserving its own label.

Raises:

Type Description
KeyError

If a name to rename is not a level of this batch.

ValueError

If a level is renamed twice with different names, or a new name is empty, contains /, collides with a level that is being kept, is the target of two renames, or belongs to a dropped root level still used to label subsequent selections from a view.

TypeError

If a new name is not a string.

Notes

The level counterpart of rename, which renames the fields within an element. The two namespaces are independent: renaming a level never touches a field name, or the reverse.

Source code in probpipe/core/_batch.py
def with_level_names(self, mapping: Mapping[str, str] | None = None, /, **kwargs: str) -> Self:
    """Rename levels ``old -> new``; shapes and elements are unchanged.

    Accepts a positional mapping, keyword pairs, or both. Every name given must
    be a level of this batch, and the result must still name each level once.

    Parameters
    ----------
    mapping : Mapping of str to str, optional
        Renames as ``{old: new}``, positional so that any level name is
        addressable even where it is not a valid keyword.
    **kwargs : str
        Renames as ``old="new"``, for the common case. A level named in both
        must be given the same new name in each.

    Returns
    -------
    Self
        A shallow copy over the same axes and elements, specified over the new
        level names, preserving its own label.

    Raises
    ------
    KeyError
        If a name to rename is not a level of this batch.
    ValueError
        If a level is renamed twice with different names, or a new name is
        empty, contains ``/``, collides with a level that is being kept, is
        the target of two renames, or belongs to a dropped root level still
        used to label subsequent selections from a view.
    TypeError
        If a new name is not a string.

    Notes
    -----
    The level counterpart of ``rename``, which renames the *fields
    within* an element. The two namespaces are independent: renaming a level
    never touches a field name, or the reverse.
    """
    positional = dict(mapping or {})
    conflicting = sorted(
        old for old, new in kwargs.items() if old in positional and positional[old] != new
    )
    if conflicting:
        raise ValueError(
            f"level {conflicting[0]!r} is renamed twice, by the positional mapping and "
            f"by a keyword; give it one new name"
        )
    renames: dict[str, str] = {**positional, **kwargs}
    unknown = [old for old in renames if old not in self.level_names]
    if unknown:
        raise KeyError(unknown_names("level", unknown, self.level_names))
    for new in renames.values():
        # Type before emptiness: None, 0 and [] are all falsy, and reporting
        # them as empty names would describe the wrong problem.
        if not isinstance(new, str):
            raise TypeError(f"level names must be strings, got {type(new).__name__}: {new!r}")
        _check_output_name(new, context="level names")

    renamed = tuple(renames.get(old, old) for old in self.level_names)
    if len(set(renamed)) != len(renamed):
        raise ValueError(
            f"renaming would duplicate a level name: {self.level_names} -> {renamed}"
        )
    return self._with_level_names(renamed)

__repr__()

The public class, the label, the levels, and the elements' structure.

A numeric batch shows its values below them.

Source code in probpipe/core/_batch.py
def __repr__(self) -> str:
    """The public class, the label, the levels, and the elements' structure.

    A numeric batch shows its values below them.
    """
    return self._repr_summary()

__len__()

The leading batch axis, batch_shape[0].

Source code in probpipe/core/_batch.py
def __len__(self) -> int:
    """The leading batch axis, ``batch_shape[0]``."""
    return self.batch_shape[0]

__iter__()

Iterate the leading batch axis, yielding views.

Source code in probpipe/core/_batch.py
def __iter__(self) -> Iterator[E | Self]:
    """Iterate the leading batch axis, yielding views."""
    return (self[index] for index in range(len(self)))

__getitem__(paths_or_positions)

Index the batch axes by position, or every element by path.

By position, a single indexer addresses the leading axis and a tuple the leading axes in order, as batch[i, j] does for an array. Each indexer is an integer, anything with __index__ such as a NumPy or JAX integer scalar, or a slice; an integer drops its axis and a slice keeps it, a whole axis being written :. The result is an element once every axis is dropped and a sub-batch view otherwise, exactly as for at_levels, which is the by-name counterpart over levels.

By path, batch["x"] addresses the node at the path x of every element, and a list or a tuple of paths, as batch["a", "g/c"], the elements cut down to those nodes. A tuple is read as a list of paths; a nested path is written with /. A batch whose elements are records answers; a batch whose elements are arrays or opaque values has no paths.

Parameters:

Name Type Description Default
paths_or_positions int, slice, str, list, or tuple

An integer, a slice, or a tuple of them addresses the batch axes; a string is read as one path, and a list or a tuple of strings as a list of paths.

required

Returns:

Type Description
E or Self or Any

An element or a sub-batch view for a position; the batch of the elements' nodes for paths.

Raises:

Type Description
IndexError

If more indexers are given than there are batch axes, or an integer is out of range for its axis.

KeyError

If the elements are records and a path is not one of their paths.

TypeError

If paths_or_positions is neither a position nor paths, such as None, a bool, ..., a set, or an array; if it mixes paths with positions; if it is a list of positions; or if it is paths and the elements have no paths, as arrays and opaque values have none.

ValueError

If a slice has a step of zero, a path is empty or has an empty name, or a list of paths is empty, as batch[()] is, names a path twice, or holds a path inside another.

Notes

The two readings never collide, an axis having no name and a path no position, which is what lets one operator serve both. The axis side is stated once here for every batch; the path side is left to _at_paths. None is not a position: it spells a whole axis in at_levels alone, where a keyword cannot take a : literal.

Source code in probpipe/core/_batch.py
def __getitem__(self, paths_or_positions: Any) -> Any:
    """Index the batch axes by position, or every element by path.

    By **position**, a single indexer addresses the leading axis and a tuple
    the leading axes in order, as ``batch[i, j]`` does for an array. Each
    indexer is an integer, anything with ``__index__`` such as a NumPy or JAX
    integer scalar, or a slice; an integer drops its axis and a slice keeps
    it, a whole axis being written ``:``. The result is an element once
    every axis is dropped and a sub-batch view otherwise, exactly as for
    :meth:`at_levels`, which is the by-name counterpart over *levels*.

    By **path**, ``batch["x"]`` addresses the node at the path ``x`` of every
    element, and a list or a tuple of paths, as ``batch["a", "g/c"]``, the
    elements cut down to those nodes. A tuple is read as a list of paths; a
    nested path is written with ``/``. A batch whose elements are records
    answers; a batch whose elements are arrays or opaque values has no
    paths.

    Parameters
    ----------
    paths_or_positions : int, slice, str, list, or tuple
        An integer, a slice, or a tuple of them addresses the batch axes; a
        string is read as one path, and a list or a tuple of strings as a list
        of paths.

    Returns
    -------
    E or Self or Any
        An element or a sub-batch view for a position; the batch of the
        elements' nodes for paths.

    Raises
    ------
    IndexError
        If more indexers are given than there are batch axes, or an integer
        is out of range for its axis.
    KeyError
        If the elements are records and a path is not one of their paths.
    TypeError
        If *paths_or_positions* is neither a position nor paths, such as ``None``, a
        ``bool``, ``...``, a set, or an array; if it mixes paths with
        positions; if it is a list of positions; or if it is paths and the
        elements have no paths, as arrays and opaque values have none.
    ValueError
        If a slice has a step of zero, a path is empty or has an empty name,
        or a list of paths is empty, as ``batch[()]`` is, names a path
        twice, or holds a path inside another.

    Notes
    -----
    The two readings never collide, an axis having no name and a path no
    position, which is what lets one operator serve both. The axis side is
    stated once here for every batch; the path side is left to
    :meth:`_at_paths`. ``None`` is not a position: it spells a whole axis in
    :meth:`at_levels` alone, where a keyword cannot take a ``:`` literal.
    """
    positions = _as_positions(paths_or_positions)
    if positions is not None:
        return self._at_axes(positions)
    return self._at_paths(
        _as_paths(
            paths_or_positions,
            action=f"index {public_class_name(type(self))} by",
            positions=True,
        ),
        tuple_given=isinstance(paths_or_positions, tuple),
    )

__contains__(path)

Whether path is a str and a path of the elements; an element is never tested.

Source code in probpipe/core/_batch.py
def __contains__(self, path: object) -> bool:
    """Whether *path* is a ``str`` and a path of the elements; an element is never tested."""
    return isinstance(path, str) and self._has_path(path)

at_levels(**levels)

Index by named level, returning an element or a sub-batch view.

Each keyword names a level of this batch and gives it an indexer: an integer, a slice, None, or a tuple of those addressing the level's axes in order. An integer drops its axis; a slice or None keeps it, None standing for the whole axis as : does. A shorter tuple fills the level's leading axes and leaves the rest whole, so a scalar draw=i on a two-axis draw level means draw=(i, None). A level not named is kept whole, and a level whose axes are all dropped is removed, yielding the inner batch or element just as positional indexing does.

A level name that is no Python identifier is passed in a mapping, as at_levels(**{"my level": 0}). The receiver is positional-only, so every level name is addressable as a keyword — including one that happens to spell a parameter of this method.

Parameters:

Name Type Description Default
**levels int, slice, None, or tuple

One indexer per named level, keyed by the level's name.

{}

Returns:

Type Description
E or Self

The element the selection reaches, or a sub-batch view over the levels that remain.

Raises:

Type Description
KeyError

If a keyword is not a level of this batch.

ValueError

If a level is given more indexers than it has axes, or a slice has a step of zero.

IndexError

If an integer is out of range for its axis.

TypeError

If an indexer is not an integer, a slice, None, or a tuple of those.

Notes

The by-name counterpart of positional [], and the level analogue of NamedTree.at_path: a path addresses a position in a tree and returns a leaf or a subtree, while named level indexers address positions here and return an element or a sub-batch. None spells a whole axis in this form alone, a keyword being unable to take a : literal; positional [] writes : and refuses None.

Source code in probpipe/core/_batch.py
def at_levels(self, /, **levels: LevelIndexer) -> E | Self:
    """Index by named level, returning an element or a sub-batch view.

    Each keyword names a level of this batch and gives it an indexer: an
    integer, a slice, ``None``, or a tuple of those addressing the level's axes
    in order. An integer drops its axis; a slice or ``None`` keeps it, ``None``
    standing for the whole axis as ``:`` does. A shorter tuple fills the
    level's leading axes and leaves the rest whole, so a scalar ``draw=i`` on a
    two-axis ``draw`` level means ``draw=(i, None)``. A level not named is kept
    whole, and a level whose axes are all dropped is removed, yielding the
    inner batch or element just as positional indexing does.

    A level name that is no Python identifier is passed in a mapping, as
    ``at_levels(**{"my level": 0})``. The receiver is positional-only, so every
    level name is addressable as a keyword — including one that happens to
    spell a parameter of this method.

    Parameters
    ----------
    **levels : int, slice, None, or tuple
        One indexer per named level, keyed by the level's name.

    Returns
    -------
    E or Self
        The element the selection reaches, or a sub-batch view over the levels
        that remain.

    Raises
    ------
    KeyError
        If a keyword is not a level of this batch.
    ValueError
        If a level is given more indexers than it has axes, or a slice has a
        step of zero.
    IndexError
        If an integer is out of range for its axis.
    TypeError
        If an indexer is not an integer, a slice, ``None``, or a tuple of
        those.

    Notes
    -----
    The by-name counterpart of positional ``[]``, and the level analogue of
    ``NamedTree.at_path``: a path addresses a position in a tree and returns a
    leaf or a subtree, while named level indexers address positions here and
    return an element or a sub-batch. ``None`` spells a whole axis in this form
    alone, a keyword being unable to take a ``:`` literal; positional ``[]``
    writes ``:`` and refuses ``None``.
    """
    unknown = [name for name in levels if name not in self.level_names]
    if unknown:
        raise KeyError(unknown_names("level", unknown, self.level_names))

    axis_index: list[int | slice] = [slice(None)] * len(self.batch_shape)
    # Where each addressed axis came from, so a complaint about an indexer
    # names the level it was given for rather than the flat axis it landed on.
    # Only addressed axes carry one; the rest cannot fail, being whole.
    where: list[str | None] = [None] * len(self.batch_shape)
    start = 0
    for level_name, group in zip(self.level_names, self.axis_groups, strict=True):
        if level_name in levels:
            given = levels[level_name]
            indexers = given if isinstance(given, tuple) else (given,)
            if len(indexers) > len(group):
                raise ValueError(
                    f"level {level_name!r} has {count(len(group), 'axis', 'axes')} but "
                    f"got {count(len(indexers), 'indexer')}"
                )
            for offset, indexer in enumerate(indexers):
                axis_index[start + offset] = slice(None) if indexer is None else indexer
                where[start + offset] = (
                    f"level {level_name!r} of size {group[0]}"
                    if len(group) == 1
                    else f"axis {offset} of level {level_name!r}, axes {group}"
                )
        start += len(group)
    return self._at_axes(tuple(axis_index), where=tuple(where))

RecordBatch(fields, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)

Bases: Batch[Record]

A batch of records sharing one RecordSpec, stored as columns.

RecordBatch(...) returns a NumericRecordBatch when every column is a numeric array and element is omitted or a NumericRecordSpec, as Record(...) returns a NumericRecord when every field is numeric. A subclass constructs its own class.

As a JAX pytree it flattens to its columns, with its spec as the static data. The label and the expression do not cross a transform, so two batches that differ only in their labels have equal treedefs and share a compilation, and a batch rebuilt from its leaves is labeled <no description> until a result boundary labels it.

Parameters:

Name Type Description Default
fields Mapping of str to array

The field columns, keyed by leaf path ("outer/a") or given as a nested mapping, which is flattened to leaf paths. Each column holds one field's values across the batch, shaped (*batch_shape, *event_shape) where the event shape is the field spec's for a NumericArraySpec and empty otherwise — so a field that is not an array takes an object array, one entry per element. The keys must be exactly the fields of element.

required
level_names str or sequence of str

One name per level, outermost first; a single string names a single level. There is no default, for the reason Batch gives: a level is named so that operations can align operands by meaning.

required
label str

The batch's label. Defaults to record(field,...), which names the top-level fields of the elements' spec in canonical order, so path-keyed and nested columns of the same fields give the same label.

None
element RecordSpec

The schema and kind spec every element satisfies. Defaults to the spec the columns imply, as a Record infers its spec from its values: an array column's axes past those the levels hold are its field's event shape, and an object column's entries decide its field's spec.

None
axes_per_level int or sequence of int

How many axes each level holds, outermost first (a single int is one level's count); they must account for every batch axis. Defaults to one axis per level, which requires as many names as there are batch axes. The sizes are read off the elements rather than restated here — they are already fixed by the data, so the only thing left to say is where one level ends and the next begins.

None
provenance Provenance

How this batch was produced.

None

Attributes:

Name Type Description
spec BatchSpec

This batch's own type, at the family kind over its elements'.

element_spec OutputSpec

The output spec of one element, whose outputs are the record's top-level fields and groups — a view on spec.

event_template RecordSpec

The structure of one element, element_spec.term_spec.

Raises:

Type Description
TypeError

If element is not a RecordSpec; if fields is not a mapping; if a column reports no shape, which is what a batch axis is read from; or if an entry of a non-array column is not admitted by its field's spec.

ValueError

If fields is empty; if its keys are not exactly the fields of element; if a column's trailing axes are not the event shape its field declares; if two columns disagree on the batch axes; if a field declares a symbolic dimension, which gives its event shape no size to split by; if a column leaves no batch axis; or if axes_per_level does not account for every batch axis, or gives a count that is not one per level.

TypeError

If level_names is not a str or a sequence of str, or axes_per_level is not an int or a sequence of ints; a generator, a set, bytes, and a mapping are refused for both.

ValueError

If an axes_per_level count is less than 1, or a level name is empty or contains /.

Notes

Construction requires at least one field, not at least one element: a zero-sized column is a batch of nothing, which is what a declared aggregate over no rows is, and batch[0:0] selects the same thing. What cannot be admitted is an empty field mapping, which fixes neither the fields nor a shape to read the batch axes from.

An object column is copied and frozen, so a caller keeping a handle on what they passed cannot afterwards write a value the batch's spec refuses. Only the pointer array is copied, so the elements stay shared. An array column is stored as given: a JAX array is already immutable, and a NumPy array is marked read-only in place, as a record marks its leaves.

Reading one element materializes it from the columns, which costs one gather per field, so iterating a batch is proportional to elements × fields. Reading a column costs nothing of the sort — prefer it where a whole field will do.

Examples:

>>> import jax.numpy as jnp
>>> from probpipe import RecordSpec
>>> batch = RecordBatch(
...     {"x": jnp.zeros((3, 2))},
...     "draw",
...     element=RecordSpec(x=(2,)),
...     label="draws",
... )
>>> batch.batch_shape
(3,)
>>> batch["x"].shape
(3, 2)
>>> batch[0].label
'draws[draw=0]'
Source code in probpipe/core/_record_batch.py
def __init__(
    self,
    fields: Mapping[str, Any],
    /,
    level_names: NamesLike,
    *,
    label: str | None = None,
    element: RecordSpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    kind = type(self).__name__
    names = _as_names(level_names, what=f"{kind} level_names")
    axes = (
        None
        if axes_per_level is None
        else _as_axis_counts(axes_per_level, what=f"{kind} axes_per_level")
    )
    if element is None:
        element = _inferred_element_term_spec(fields, _batch_axis_count(names, axes), kind=kind)
    spec = _record_element_term_spec(element, kind=kind)
    store = _leaf_keyed_columns(fields, spec, kind=kind)
    # Derived from the validated spec, so a path-keyed and a nested mapping of
    # the same columns read alike, as a ``Record``'s top-level fields do.
    label = _derived_record_name(spec.children) if label is None else label

    batch_shape = _batch_shape_of(store, spec, kind=kind)
    groups = _axis_groups_for(batch_shape, names, axes, kind=kind)
    type(self)._check_columns(store, spec, kind=kind)
    store = {
        path: _frozen_object_column(column) if _is_object_array(column) else _read_only(column)
        for path, column in store.items()
    }

    object.__setattr__(self, "_columns", store)
    self._init_batch(
        BatchSpec._from_groups(spec, groups, names),
        label=label,
        provenance=provenance,
    )

event_template property

The structure of one element, element_spec.term_spec.

raw property

The storage view: the nested mapping of the raw columns.

Each column is its field's raw batch form, the stacked array for an array field and the frozen object array for any other field. A node's columns are read from the mapping, as batch.raw["g"]["x"].

The nesting is built on the first read and kept, and each read returns a new dict over the columns that the caller may change. A batch holding a traced column keeps nothing.

select(*paths, **mapping)

Batch views of the nodes at paths, keyed for splatting into a call.

The batch counterpart of select, keyed the same way: a positional path is keyed by its last name, so select("a", "g/c") has the keys "a" and "c", and a keyword names the key, so select(x="g/c") keys the view of g/c under "x". A path to a field gives a one-field view, and a path to a group the batch of the group's records. Each entry is a RecordBatch view rather than a bare array, so splatting the result into a Function call carries the level names an operation aligns operands by.

Parameters:

Name Type Description Default
*paths str

Paths to select, each keyed by its last name in the result.

()
**mapping str

Paths to select, each keyed by its keyword in the result.

{}

Returns:

Type Description
dict of str to RecordBatch

One view per path, at this batch's levels, the positional paths first.

Raises:

Type Description
KeyError

If a path is not a path of the elements.

TypeError

If a path is not a string.

ValueError

If a path is empty or has an empty name, or two entries would take the same key, as select("s1/theta", "s2/theta") would.

Source code in probpipe/core/_record_batch.py
def select(self, *paths: str, **mapping: str) -> dict[str, Self]:
    """Batch views of the nodes at *paths*, keyed for splatting into a call.

    The batch counterpart of :meth:`~probpipe.Record.select`, keyed the same
    way: a positional path is keyed by its last name, so ``select("a",
    "g/c")`` has the keys ``"a"`` and ``"c"``, and a keyword names the key,
    so ``select(x="g/c")`` keys the view of ``g/c`` under ``"x"``. A path to
    a field gives a one-field view, and a path to a group the batch of the
    group's records. Each entry is a ``RecordBatch`` view rather than a bare
    array, so splatting the result into a ``Function`` call carries the
    level names an operation aligns operands by.

    Parameters
    ----------
    *paths : str
        Paths to select, each keyed by its last name in the result.
    **mapping : str
        Paths to select, each keyed by its keyword in the result.

    Returns
    -------
    dict of str to RecordBatch
        One view per path, at this batch's levels, the positional paths first.

    Raises
    ------
    KeyError
        If a path is not a path of the elements.
    TypeError
        If a path is not a string.
    ValueError
        If a path is empty or has an empty name, or two entries would take
        the same key, as ``select("s1/theta", "s2/theta")`` would.
    """
    return {key: self._view_at(path) for key, path in _keyed_paths(paths, mapping).items()}

select_all()

Every top-level part as a batch view, keyed by its own name.

Keyed by top-level name rather than by leaf path, as select_all is, so the result splats into a call: a name binds to a parameter where a /-path could not. A top-level name that is an interior node gives the sub-batch beneath it, so the parts cover the batch between them.

Source code in probpipe/core/_record_batch.py
def select_all(self) -> dict[str, Self]:
    """Every **top-level** part as a batch view, keyed by its own name.

    Keyed by top-level name rather than by leaf path, as
    :meth:`~probpipe.Record.select_all` is, so the result splats into a call:
    a name binds to a parameter where a ``/``-path could not. A top-level
    name that is an interior node gives the sub-batch beneath it, so the parts
    cover the batch between them.
    """
    return self.select(*self.event_template.children)

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

Rename or move nodes old -> new within every element.

The element counterpart of with_level_names, which renames the levels: the two namespaces are independent, and renaming one leaves the other unchanged. Each key is the exact path of a node of the elements and each target its new exact path, under the rule of rename. Each column is stored under its field's new key, so no stored value changes.

Parameters:

Name Type Description Default
renames Mapping of str to str

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

None
**keyword_renames str

The new path of each top-level node of the elements, keyed by the node's name.

{}

Returns:

Type Description
Self

A batch over the same values and levels, its elements' nodes renamed.

Raises:

Type Description
KeyError

If a key is not the path of a node of the elements.

TypeError

As rename raises it.

ValueError

As rename raises it.

Source code in probpipe/core/_record_batch.py
def rename(self, renames: Mapping[str, str] | None = None, /, **keyword_renames: str) -> Self:
    """Rename or move nodes ``old -> new`` within every element.

    The element counterpart of :meth:`~probpipe.core._batch.Batch.with_level_names`,
    which renames the *levels*: the two namespaces are independent, and
    renaming one leaves the other unchanged. Each key is the exact path of a
    node of the elements and each target its new exact path, under the rule
    of :meth:`~probpipe.core.named_tree.NamedTree.rename`. Each
    column is stored under its field's new key, so no stored value changes.

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

    Returns
    -------
    Self
        A batch over the same values and levels, its elements' nodes renamed.

    Raises
    ------
    KeyError
        If a key is not the path of a node of the elements.
    TypeError
        As :meth:`~probpipe.core.named_tree.NamedTree.rename` raises it.
    ValueError
        As :meth:`~probpipe.core.named_tree.NamedTree.rename` raises it.
    """
    template = self.event_template
    resolved_renames = template._resolve_path_renames(renames, keyword_renames)
    moved = template._moved_leaf_paths(resolved_renames)
    return self._rebuilt(
        {moved[path]: column for path, column in self._columns.items()},
        template.rename(resolved_renames),
    )

without(*paths)

Drop the fields or subtrees at paths from every element.

Each path is a key, dropping one field, or a partial path, dropping the subtree beneath it. The surviving fields keep their order and their specs, and the batch axes are unchanged.

Parameters:

Name Type Description Default
*paths str

The keys and partial paths to drop.

()

Returns:

Type Description
Self

A batch over the surviving columns, at the same levels.

Raises:

Type Description
KeyError

If a path is not a field or an interior node of the elements.

ValueError

If every field would be dropped — a batch of records with no fields is not a value.

Source code in probpipe/core/_record_batch.py
def without(self, *paths: str) -> Self:
    """Drop the fields or subtrees at *paths* from every element.

    Each path is a key, dropping one field, or a partial path, dropping the
    subtree beneath it. The surviving fields keep their order and their specs,
    and the batch axes are unchanged.

    Parameters
    ----------
    *paths : str
        The keys and partial paths to drop.

    Returns
    -------
    Self
        A batch over the surviving columns, at the same levels.

    Raises
    ------
    KeyError
        If a path is not a field or an interior node of the elements.
    ValueError
        If every field would be dropped — a batch of records with no fields
        is not a value.
    """
    read_paths = _as_path_arguments(paths, action="call without() with")
    for path in read_paths:
        self._check_path(path)
    kept = self.event_template.without(*read_paths)
    return self._rebuilt({path: self._columns[path] for path in kept}, kept)

replace(_updates=None, /, **updates)

Replace the values at the given paths, across the whole batch.

Each replacement is that field's values for every element, shaped (*batch_shape, *event_shape) — the same form the field is read back in, not one element's value. Every path must already exist: this edits, it does not add. An untouched field keeps its spec; a replaced one takes the spec its new values imply.

Parameters:

Name Type Description Default
_updates Mapping of str to Any

The replacements keyed by field key, which may address a field at any depth. Passing it together with keyword updates raises.

None
**updates Any

The replacements keyed by the name of a top-level field.

{}

Returns:

Type Description
Self

A batch over the edited columns, at the same levels.

Raises:

Type Description
KeyError

If a path is not a field of the elements.

ValueError

If no updates are given, or a replacement does not carry the batch axes.

Source code in probpipe/core/_record_batch.py
def replace(self, _updates: Mapping[str, Any] | None = None, /, **updates: Any) -> Self:
    """Replace the values at the given paths, across the whole batch.

    Each replacement is that field's values for *every* element, shaped
    ``(*batch_shape, *event_shape)`` — the same form the field is read back
    in, not one element's value. Every path must already exist: this edits,
    it does not add. An untouched field keeps its spec; a replaced one takes
    the spec its new values imply.

    Parameters
    ----------
    _updates : Mapping of str to Any, optional
        The replacements keyed by field key, which may address a field at any
        depth. Passing it together with keyword updates raises.
    **updates : Any
        The replacements keyed by the name of a top-level field.

    Returns
    -------
    Self
        A batch over the edited columns, at the same levels.

    Raises
    ------
    KeyError
        If a path is not a field of the elements.
    ValueError
        If no updates are given, or a replacement does not carry the batch
        axes.
    """
    if _updates is not None and updates:
        raise ValueError("replace() takes either a mapping or keyword updates, not both")
    edits: dict[str, Any] = {}
    declared: dict[str, TermSpec] = {}
    for path, value in (_updates or updates).items():
        edits[path], spec = _unwrapped_field(value)
        if spec is not None:
            declared[path] = spec
    if not edits:
        raise ValueError(f"{type(self).__name__}.replace() needs at least one update")
    unknown = [path for path in edits if path not in self._columns]
    if unknown:
        raise KeyError(
            f"replace() can only change existing fields: "
            f"{unknown_names('field', unknown, self._columns)}"
        )
    columns = {**self._columns, **edits}
    return self._rebuilt(
        columns, _element_template_for(columns, self, edited=set(edits), declared=declared)
    )

__and__(other)

Merge this batch's elements with other's by top-level name, element by element.

Both batches must span the same axes under the same level names, since the result's elements pair up one for one. The merge is shallow, as Record.__and__ states: a top-level name, a field or a group, in both batches raises. Each side keeps its own fields' specs.

Parameters:

Name Type Description Default
other RecordBatch

The batch whose fields are added.

required

Returns:

Type Description
Self

A batch over both sets of columns, with this batch's fields first.

Raises:

Type Description
TypeError

If other is not a batch of records.

ValueError

If the two disagree on their levels or axes, or a top-level name is in both.

Source code in probpipe/core/_record_batch.py
def __and__(self, other: Self) -> Self:
    """Merge this batch's elements with *other*'s by top-level name, element by element.

    Both batches must span the same axes under the same level names, since
    the result's elements pair up one for one. The merge is shallow, as
    :meth:`Record.__and__` states: a top-level name, a field or a group, in
    both batches raises. Each side keeps its own fields' specs.

    Parameters
    ----------
    other : RecordBatch
        The batch whose fields are added.

    Returns
    -------
    Self
        A batch over both sets of columns, with this batch's fields first.

    Raises
    ------
    TypeError
        If *other* is not a batch of records.
    ValueError
        If the two disagree on their levels or axes, or a top-level name is
        in both.
    """
    if not isinstance(other, RecordBatch):
        raise TypeError(
            f"cannot merge {type(self).__name__} with {type(other).__name__}. "
            "Pass another batch of records"
        )
    if (self.axis_groups, self.level_names) != (other.axis_groups, other.level_names):
        raise ValueError(
            f"cannot merge batches with different levels: "
            f"{format_levels(self.level_names, self.axis_groups)} and "
            f"{format_levels(other.level_names, other.axis_groups)}"
        )
    _check_no_shared_top_level_names(
        self.event_template, other.event_template, operands="the two batches of records"
    )
    merged = self.event_template & (other.event_template)
    return self._rebuilt({**self._columns, **other._columns}, merged)

map(f, /, *args, **kwargs)

Apply f to every field's values, keeping the structure.

What a batch presents at each field is that field's values across the batch, so that is what f receives — one call per field, vectorized, rather than one per element. A function that preserves the batch axes therefore yields a batch of the same shape; each field takes the spec its result implies.

Parameters:

Name Type Description Default
f callable

Called as f(column, *args, **kwargs) on each field's stored column.

required
*args Any

Further positional arguments of f, the same for every field.

()
**kwargs Any

Further keyword arguments of f, the same for every field.

{}

Returns:

Type Description
Self

A batch over the results, at the same levels.

Raises:

Type Description
ValueError

If a result does not carry the batch axes.

Source code in probpipe/core/_record_batch.py
def map(self, f: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Self:
    """Apply *f* to every field's values, keeping the structure.

    What a batch presents at each field is that field's values across the
    batch, so that is what *f* receives — one call per field, vectorized,
    rather than one per element. A function that preserves the batch axes
    therefore yields a batch of the same shape; each field takes the spec its
    result implies.

    Parameters
    ----------
    f : callable
        Called as ``f(column, *args, **kwargs)`` on each field's stored column.
    *args : Any
        Further positional arguments of *f*, the same for every field.
    **kwargs : Any
        Further keyword arguments of *f*, the same for every field.

    Returns
    -------
    Self
        A batch over the results, at the same levels.

    Raises
    ------
    ValueError
        If a result does not carry the batch axes.
    """
    columns = {path: f(column, *args, **kwargs) for path, column in self._columns.items()}
    return self._rebuilt(columns, _element_template_for(columns, self, edited=set(columns)))

map_with_keys(f, /, *args, **kwargs)

map, with each field's leaf path passed as the first argument.

Source code in probpipe/core/_record_batch.py
def map_with_keys(self, f: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Self:
    """:meth:`map`, with each field's leaf path passed as the first argument."""
    columns = {path: f(path, column, *args, **kwargs) for path, column in self._columns.items()}
    return self._rebuilt(columns, _element_template_for(columns, self, edited=set(columns)))

stack(records, *, level_name, element=None, label=None) classmethod

Stack records into a batch with one level of (len(records),).

Parameters:

Name Type Description Default
records list of Record

The elements, all conforming to one template. At least one.

required
level_name str

Names the level the stacking mints. Required, since the operation doing the stacking is what knows what the axis means.

required
element RecordSpec

The spec every element satisfies. Taken from the first record when omitted, which is exact whenever the records were built against a shared declaration, with each opaque field typed by what its values share, as an OpaqueBatch types its elements.

None
label str

The batch's label. Taken from the first record when omitted — a batch of draw records is about draw, so the label is derived from what is being stacked rather than invented. A caller with a better label passes one.

None

Returns:

Type Description
RecordBatch

The batch, with batch_shape == (len(records),). Called on RecordBatch, it is a NumericRecordBatch when the stacked columns are all numeric, by the rule RecordBatch states.

Raises:

Type Description
ValueError

If records is empty, or a record's fields are not exactly the spec's, naming the record's position and what differs.

Notes

Nested templates stack like any other: a column is keyed by leaf path, so a nested field is one column and nesting costs the stacking nothing.

Source code in probpipe/core/_record_batch.py
@classmethod
def stack(
    cls,
    records: list[Record],
    *,
    level_name: str,
    element: RecordSpec | None = None,
    label: str | None = None,
) -> Self:
    """Stack records into a batch with one level of ``(len(records),)``.

    Parameters
    ----------
    records : list of Record
        The elements, all conforming to one template. At least one.
    level_name : str
        Names the level the stacking mints. Required, since the operation
        doing the stacking is what knows what the axis means.
    element : RecordSpec, optional
        The spec every element satisfies. Taken from the first record when
        omitted, which is exact whenever the records were built against a
        shared declaration, with each opaque field typed by what its values
        share, as an ``OpaqueBatch`` types its elements.
    label : str, optional
        The batch's label. Taken from the first record when omitted — a batch of
        ``draw`` records is about ``draw``, so the label is derived from what is
        being stacked rather than invented. A caller with a better label passes one.

    Returns
    -------
    RecordBatch
        The batch, with ``batch_shape == (len(records),)``. Called on
        ``RecordBatch``, it is a ``NumericRecordBatch`` when the stacked
        columns are all numeric, by the rule :class:`RecordBatch` states.

    Raises
    ------
    ValueError
        If *records* is empty, or a record's fields are not exactly the
        spec's, naming the record's position and what differs.

    Notes
    -----
    Nested templates stack like any other: a column is keyed by leaf path, so
    a nested field is one column and nesting costs the stacking nothing.
    """
    if not records:
        raise ValueError(f"{cls.__name__}.stack needs at least one record")
    kind = f"{cls.__name__}.stack"
    spec = _record_element_term_spec(
        element if element is not None else records[0].event_template, kind=kind
    )
    if element is None:
        spec = _shared_opaque_types(spec, records)
    fields = spec.keys()
    for position, record in enumerate(records):
        # Checked rather than left to a KeyError from the column loop: a
        # record with *extra* fields raises nothing at all there, and the
        # batch's spec would silently become a false statement about it.
        if tuple(record.keys()) != tuple(fields):
            raise ValueError(
                f"{kind}: record {position} has fields {list(record.keys())}, "
                f"expected {list(fields)}"
            )
    leaves = [dict(record._walk_leaves()) for record in records]
    columns = {
        key: _stack_column([stored[key] for stored in leaves], spec[key], kind=kind)
        for key in fields
    }
    return cls(
        columns,
        (level_name,),
        element=spec,
        label=label if label is not None else records[0].label,
    )

__eq__(other)

Whether other is the same class, equally specified, with equal columns.

Equality is structural over the stored columns, compared field by field. A batch is unhashable for the reason an array-carrying container usually is — see __hash__.

Source code in probpipe/core/_record_batch.py
def __eq__(self, other: object) -> bool:
    """Whether *other* is the same class, equally specified, with equal columns.

    Equality is structural over the stored columns, compared field by field.
    A batch is unhashable for the reason an array-carrying container usually
    is — see :attr:`__hash__`.
    """
    # Identity first, so reflexivity holds for a batch carrying NaN, which
    # elementwise comparison would deny.
    if self is other:
        return True
    if type(self) is not type(other):
        return NotImplemented
    if self._spec != other._spec:
        return False
    if self._columns.keys() != other._columns.keys():
        # Equal specs with unequal stored columns means one of the two is
        # malformed. Comparing only the columns *self* has would call it
        # equal, and the mirror comparison would raise.
        return False
    for path, column in self._columns.items():
        if not _columns_equal(column, other._columns[path]):
            return False
    return True

NumericRecordBatch(fields, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)

Bases: RecordBatch

A RecordBatch whose every column is a numeric array.

The all-numeric specialization, carrying a NumericRecordSpec: a bare pytree of arrays whose leading axes are the batch_shape, so its columns are the leaves jit / vmap / grad traverse. The batch itself is rebuilt only under a transform that keeps every batch axis or removes all of them; see the module docstring. It adds the batched flat layout, to_vector and from_vector.

Construction is that of RecordBatch, narrowed: element, given or inferred from the columns, must describe an all-numeric element, and every column must carry a numeric dtype.

Parameters:

Name Type Description Default
fields Mapping of str to array

The numeric columns, keyed by leaf path or given as a nested mapping, each shaped (*batch_shape, *event_shape).

required
level_names str or sequence of str

One name per level, outermost first; a single string names a single level.

required
label str

The batch's label. Defaults to record(field,...), which names the top-level fields of the elements' spec, as for RecordBatch.

None
element RecordSpec

The all-numeric schema every element satisfies. Defaults to the spec the columns imply.

None
axes_per_level int or sequence of int

How many axes each level holds, outermost first (a single int is one level's count). Defaults to one axis per level.

None
provenance Provenance

How this batch was produced.

None

Raises:

Type Description
TypeError

If element does not describe an all-numeric element, or a column is not a numeric array.

TypeError

If level_names is not a str or a sequence of str, or axes_per_level is not an int or a sequence of ints; a generator, a set, bytes, and a mapping are refused for both.

ValueError

If an axes_per_level count is less than 1, or a level name is empty or contains /.

Source code in probpipe/core/_numeric_record_batch.py
def __init__(
    self,
    fields: Mapping[str, Any],
    /,
    level_names: NamesLike,
    *,
    label: str | None = None,
    element: RecordSpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    kind = type(self).__name__
    names = _as_names(level_names, what=f"{kind} level_names")
    axes = (
        None
        if axes_per_level is None
        else _as_axis_counts(axes_per_level, what=f"{kind} axes_per_level")
    )
    if element is None:
        n_batch = _batch_axis_count(names, axes)
        element = _inferred_element_term_spec(fields, n_batch, kind=kind)
    template = _record_element_term_spec(element, kind=type(self).__name__)
    if not isinstance(template, NumericRecordSpec):
        others = [k for k in template if not isinstance(template[k], NumericArraySpec)]
        if not others:
            raise TypeError(
                f"{kind}: element must be a NumericRecordSpec, got {type(template).__name__}"
            )
        raise TypeError(
            f"{kind} requires every field to be a numeric array, but {others} are not; "
            f"use RecordBatch for fields that are not numeric arrays"
        )
    super().__init__(
        fields,
        names,
        element=element,
        axes_per_level=axes,
        provenance=provenance,
        label=label,
    )

event_template property

The numeric structure of one element, element_spec.term_spec.

shape property

The sole field's full shape, (*batch_shape, *event_shape).

dtype property

The sole field's dtype.

ndim property

The rank of the sole field's values, batch axes included.

__repr__()

The class, the label, and the levels, then one line for each field with its values.

Each line gives a field's path and its stored column, batch axes leading, as NumPy prints it, so np.set_printoptions sets the precision and shortens a large column with ..., and a shortened column ends with its shape. Only the entries shown are read from the device. Inside a JAX trace, where the columns are tracers, the repr is the summary of the label, the levels, and the field paths.

A batch of records of summaries, whose provenance describes how each column of each element was computed, as the batch summarize returns for a batch of laws does, shows one table for each element instead, as a record's repr states. Each table is titled by its element's levels, as law=0, each title is indented by two spaces and each table by four, and the elements are shortened to edgeitems at each end when their rows number more than NumPy's threshold. The line that states how the columns were computed follows each table, or follows the last when every element's line is the same.

Source code in probpipe/core/_numeric_record_batch.py
def __repr__(self) -> str:
    """The class, the label, and the levels, then one line for each field with its values.

    Each line gives a field's path and its stored column, batch axes
    leading, as NumPy prints it, so ``np.set_printoptions`` sets the
    precision and shortens a large column with ``...``, and a shortened
    column ends with its shape. Only the entries shown are read from the
    device. Inside a JAX trace, where the columns are tracers, the repr is
    the summary of the label, the levels, and the field paths.

    A batch of records of summaries, whose provenance describes how each
    column of each element was computed, as the batch ``summarize`` returns
    for a batch of laws does, shows one table for each element instead, as
    a record's repr states. Each table is titled by its element's levels, as
    ``law=0``, each title is indented by two spaces and each table by four,
    and the elements are shortened to ``edgeitems`` at each end when their
    rows number more than NumPy's ``threshold``. The line that states how
    the columns were computed follows each table, or follows the last when
    every element's line is the same.
    """
    tables = batch_tables_text(self, self._repr_summary(structure=False))
    if tables is not None:
        return tables
    return summary_with_values(
        self._repr_summary(structure=False),
        format_rows(self._value_rows(), VALUE_INDENT),
        alone=self._repr_summary(),
    )

__str__()

The lines of the repr's values or tables alone, or the summary inside a JAX trace.

Source code in probpipe/core/_numeric_record_batch.py
def __str__(self) -> str:
    """The lines of the repr's values or tables alone, or the summary inside a JAX trace."""
    tables = batch_tables_text(self, None)
    if tables is not None:
        return tables
    rows = format_rows(self._value_rows())
    return self._repr_summary() if rows is None else rows

__array__(dtype=None, copy=None)

The sole field's values as a numpy array.

Source code in probpipe/core/_numeric_record_batch.py
def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray:
    """The sole field's values as a numpy array."""
    leaf = self._sole_field()
    array = np.asarray(leaf, dtype=dtype) if dtype is not None else np.asarray(leaf)
    return array.copy() if copy else array

__jax_array__()

The sole field's values as a jax.Array.

Source code in probpipe/core/_numeric_record_batch.py
def __jax_array__(self) -> Array:
    """The sole field's values as a ``jax.Array``."""
    return jnp.asarray(self._sole_field())

to_vector()

Every element's flat vector, stacked.

Returns:

Type Description
Array

Shape (*batch_shape, vector_size): one raveled vector per element, fields visited in the template's canonical order, each field's event axes raveled and the fields concatenated. The inverse is from_vector.

Notes

Distinct from reading the columns, which keeps each field whole and its event axes intact. The batch axes are left as they are: a multi-level batch keeps its levels as the leading axes of the result, so the flat dimension is always the last one and the levels read outermost-first.

Source code in probpipe/core/_numeric_record_batch.py
def to_vector(self) -> Array:
    """Every element's flat vector, stacked.

    Returns
    -------
    Array
        Shape ``(*batch_shape, vector_size)``: one raveled vector per
        element, fields visited in the template's canonical order, each
        field's event axes raveled and the fields concatenated. The inverse
        is :meth:`from_vector`.

    Notes
    -----
    Distinct from reading the columns, which keeps each field whole and its
    event axes intact. The batch axes are left as they are: a multi-level
    batch keeps its levels as the leading axes of the result, so the flat
    dimension is always the last one and the levels read outermost-first.
    """
    batch_shape = self.batch_shape
    template = self.event_template
    leaf_shapes = template.leaf_shapes
    return jnp.concatenate(
        [
            # The field's own flat width rather than ``-1``: an empty batch
            # axis leaves nothing for ``-1`` to be inferred from.
            jnp.reshape(
                jnp.asarray(self._columns[key]),
                (*batch_shape, int(np.prod(leaf_shapes[key], dtype=int))),
            )
            for key in template
        ],
        axis=-1,
    )

from_vector(spec, vec, *, level_names, axes_per_level=None, label=None) classmethod

Rebuild a batch from its elements' flat vectors, inverting to_vector.

Parameters:

Name Type Description Default
spec NumericRecordSpec

The flat layout: field names, event shapes, and canonical order. Every leaf must be a NumericArraySpec.

required
vec Array

Shape (*batch_shape, vector_size) — the trailing axis is the flat dimension, and every leading axis is a batch axis.

required
level_names str or sequence of str

One name per level of the reconstructed batch, outermost first; a single string names a single level. Required for the reason RecordBatch.stack states, and plural because vec may carry several batch axes: naming them is how a multi-level batch round-trips.

required
axes_per_level int or sequence of int

How many axes each level holds, as for the constructor. Omitted, a single name takes all of vec's batch axes as one level and several names take one axis each. The first is why a draw of several axes reconstructs without naming each: a sample_shape is one multiplicity however many axes it spans.

None
label str or None

Keyword-only. The reconstructed batch's label; None, the default, derives record(field,...) from the spec's top-level fields, as the constructor does.

None

Returns:

Type Description
NumericRecordBatch

The batch, satisfying batch.to_vector() == vec.

Raises:

Type Description
TypeError

If the spec contains a non-array leaf; if vec has no batch axis — reconstruct a single value with NumericRecord.from_vector; if label is omitted and the spec has no fields to derive it from; or if spec is a string, which is a label passed first in the earlier form.

ValueError

If the trailing axis is not spec.vector_size, or if the level names do not account for vec's leading axes.

Examples:

A two-level batch round-trips when both levels are named:

>>> import jax.numpy as jnp
>>> from probpipe import RecordSpec
>>> spec = RecordSpec(x=(2,))
>>> batch = NumericRecordBatch(
...     {"x": jnp.zeros((4, 5, 2))},
...     ("chain", "draw"),
...     element=spec,
...     label="post",
... )
>>> rebuilt = NumericRecordBatch.from_vector(
...     spec, batch.to_vector(), level_names=("chain", "draw"), label="post")
>>> rebuilt.batch_shape
(4, 5)
Source code in probpipe/core/_numeric_record_batch.py
@classmethod
@refuses_label_first("spec", "vec")
def from_vector(
    cls,
    spec: NumericRecordSpec,
    vec: Array,
    *,
    level_names: NamesLike,
    axes_per_level: AxisCountsLike | None = None,
    label: str | None = None,
) -> Self:
    """Rebuild a batch from its elements' flat vectors, inverting :meth:`to_vector`.

    Parameters
    ----------
    spec : NumericRecordSpec
        The flat layout: field names, event shapes, and canonical order.
        Every leaf must be a NumericArraySpec.
    vec : Array
        Shape ``(*batch_shape, vector_size)`` — the trailing axis is the flat
        dimension, and every leading axis is a batch axis.
    level_names : str or sequence of str
        One name per level of the reconstructed batch, outermost first; a
        single string names a single level. Required for the reason
        :meth:`RecordBatch.stack` states, and plural because *vec* may carry
        several batch axes: naming them is how a multi-level batch round-trips.
    axes_per_level : int or sequence of int, optional
        How many axes each level holds, as for the constructor. Omitted, a
        single name takes **all** of *vec*'s batch axes as one level and several
        names take one axis each. The first is why a draw of several axes
        reconstructs without naming each: a ``sample_shape`` is one multiplicity
        however many axes it spans.
    label : str or None
        Keyword-only. The reconstructed batch's label; ``None``, the default,
        derives ``record(field,...)`` from the spec's top-level fields, as the
        constructor does.

    Returns
    -------
    NumericRecordBatch
        The batch, satisfying ``batch.to_vector() == vec``.

    Raises
    ------
    TypeError
        If the spec contains a non-array leaf; if *vec* has no batch
        axis — reconstruct a single value with ``NumericRecord.from_vector``;
        if *label* is omitted and the spec has no fields to derive it from;
        or if *spec* is a string, which is a label passed first in the
        earlier form.
    ValueError
        If the trailing axis is not ``spec.vector_size``, or if the level
        names do not account for *vec*'s leading axes.

    Examples
    --------
    A two-level batch round-trips when both levels are named:

    >>> import jax.numpy as jnp
    >>> from probpipe import RecordSpec
    >>> spec = RecordSpec(x=(2,))
    >>> batch = NumericRecordBatch(
    ...     {"x": jnp.zeros((4, 5, 2))},
    ...     ("chain", "draw"),
    ...     element=spec,
    ...     label="post",
    ... )
    >>> rebuilt = NumericRecordBatch.from_vector(
    ...     spec, batch.to_vector(), level_names=("chain", "draw"), label="post")
    >>> rebuilt.batch_shape
    (4, 5)
    """
    vec = jnp.asarray(vec)
    if vec.ndim < 2:
        raise TypeError(
            f"{cls.__name__}.from_vector takes a batched matrix, shaped "
            f"(*batch_shape, vector_size); got shape {tuple(vec.shape)}. Reconstruct a "
            f"single value with NumericRecord.from_vector"
        )
    if vec.shape[-1] != spec.vector_size:
        raise ValueError(
            f"{cls.__name__}.from_vector: the trailing axis is {vec.shape[-1]}, expected "
            f"{spec.vector_size} for this spec"
        )
    batch_shape = tuple(vec.shape[:-1])
    columns: dict[str, Any] = {}
    offset = 0
    for key, declared in spec._walk_leaves():
        if not isinstance(declared, NumericArraySpec):
            raise TypeError(
                f"{cls.__name__}.from_vector: field {key!r} must have a NumericArraySpec, "
                f"got {type(declared).__name__}"
            )
        event_shape = declared.shape
        size = int(np.prod(event_shape, dtype=int))
        block = jnp.reshape(vec[..., offset : offset + size], (*batch_shape, *event_shape))
        # Concatenating promoted the fields to one dtype, so a field that
        # declares its own is cast back to it — otherwise the reconstruction
        # contradicts the very spec it was rebuilt from.
        if declared.dtype is not None:
            block = block.astype(declared.dtype)
        columns[key] = block
        offset += size
    names = _as_names(level_names, what=f"{cls.__name__}.from_vector level_names")
    if axes_per_level is None and len(names) == 1:
        axes_per_level = (len(batch_shape),)
    return cls(
        columns,
        names,
        element=spec,
        axes_per_level=axes_per_level,
        label=label,
    )

NumericArrayBatch(values, /, level_names, *, label, element=None, axes_per_level=None, provenance=None)

Bases: Batch[NumericArray]

A batch of numeric arrays sharing one NumericArraySpec.

Storage is a single array with the batch axes leading — the split RecordBatch uses, with one column instead of many. This is where a draw level lives for an array-valued law. As a JAX pytree it flattens to that array with its spec as the static data, so the label and the expression do not cross a transform, and a batch rebuilt from its leaves is labeled <no description> until a result boundary labels it.

Parameters:

Name Type Description Default
values array - like

One array holding every element, shaped (*batch_shape, *event_shape). Stored verbatim in its native form, as a NumericArray's value is, so a lazy or disk-backed column is not materialised to be batched, and a NumPy array is marked read-only in place.

required
level_names str or sequence of str

One name per level, outermost first; a single string names one level.

required
label str

The batch's label, required, as an unnamed array's and an Opaque's are. A batch is what an operation returns, and the label is what says which one it is; a class-name default would label every batch in a pipeline alike.

required
element NumericArraySpec

The spec every element satisfies. Its shape is the event shape, so it is what splits the stored array's axes into batch and event. Defaults to the spec the array implies, as a NumericArray infers its spec from its value: the axes past those the levels hold are the event shape, and the array's dtype is the elements' dtype.

None
axes_per_level int or sequence of int

How many axes each level holds, outermost first (a single int is one level's count); they must account for every batch axis. Defaults to one axis per level, which requires as many names as there are batch axes. The sizes are read off the elements rather than restated here — they are already fixed by the data, so the only thing left to say is where one level ends and the next begins.

None
provenance Provenance

How this batch was produced.

None

Raises:

Type Description
TypeError

If element is not a NumericArraySpec, or values does not convert to an array.

TypeError

Also if the stored array's dtype is one the declared element does not admit — a cross-kind conversion — or if the store reports no single dtype while the element declares one, which leaves the claim unsubstantiated.

ValueError

If values has fewer axes than the event shape it must end with, which would leave no batch axis; if its trailing axes are not that event shape; if a declared dimension is symbolic, which gives the event shape no size to split by; if values has fewer axes than the levels hold, when the elements' spec is inferred; or if axes_per_level does not account for every batch axis, or gives a count that is not one per level.

TypeError

If level_names is not a str or a sequence of str, or axes_per_level is not an int or a sequence of ints; a generator, a set, bytes, and a mapping are refused for both.

ValueError

If an axes_per_level count is less than 1, or a level name is empty or contains /.

Notes

Selection yields the element kind, as it does for every batch: batch[i] is a NumericArray. It materializes, so each element takes the derived label and inherits this batch's lineage.

Source code in probpipe/core/_numeric_array_batch.py
def __init__(
    self,
    values: Any,
    /,
    level_names: NamesLike,
    *,
    label: str,
    element: NumericArraySpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    names = _as_names(level_names, what="NumericArrayBatch level_names")
    axes = (
        None
        if axes_per_level is None
        else _as_axis_counts(axes_per_level, what="NumericArrayBatch axes_per_level")
    )
    if element is None:
        element = _inferred_element_term_spec(values, _batch_axis_count(names, axes))
    if not isinstance(element, NumericArraySpec):
        raise TypeError(
            f"NumericArrayBatch: element must be a NumericArraySpec, "
            f"got {type(element).__name__}"
        )
    event_shape = tuple(element.shape)
    symbolic = [axis for axis in event_shape if not isinstance(axis, int)]
    if symbolic:
        sizes = ", ".join(f"{name}=..." for name in symbolic)
        raise ValueError(
            f"NumericArrayBatch: element shape {element.shape} has unbound "
            f"symbolic dimensions. Bind them first with element.with_dim_sizes({sizes})"
        )
    if not _is_numeric_leaf(values):
        raise TypeError(_not_numeric("NumericArrayBatch", "values", values))
    stored = _event_shape_of(values)
    n_event = len(event_shape)
    if n_event and stored[len(stored) - n_event :] != event_shape:
        raise ValueError(
            f"NumericArrayBatch: values have shape {stored}, but element declares "
            f"event shape {event_shape}, which the trailing axes must match"
        )
    # The batch asserts *element* of every element, so the store's own
    # dtype has to satisfy it.
    dtype = _numpy_dtype_of(values)
    if element.dtype is not None:
        if dtype is None:
            # A heterogeneous store has no single dtype to check a pinned
            # one against, so the claim is unsupportable either way.
            raise TypeError(
                f"NumericArrayBatch: values have no single dtype to check against the "
                f"declared {np.dtype(element.dtype)}. Omit the dtype from "
                f"element, or pass values with one dtype"
            )
        if not np.can_cast(dtype, element.dtype, casting="same_kind"):
            raise TypeError(
                _uncastable_dtype("NumericArrayBatch: values", dtype, np.dtype(element.dtype))
            )
    batch_shape = stored[: len(stored) - n_event] if n_event else stored
    if not batch_shape:
        raise ValueError(
            f"NumericArrayBatch: values of shape {stored} have no batch axis before the "
            f"event shape {event_shape}; use NumericArray for a single value"
        )

    groups = _axis_groups_for(batch_shape, names, axes, kind="NumericArrayBatch")
    object.__setattr__(self, "_values", _read_only(values))
    self._init_batch(
        BatchSpec._from_groups(element, groups, names),
        label=label,
        provenance=provenance,
    )

raw property

The storage view: the stored array with the batch axes leading, in native form. Untracked.

shape property

The store's full shape, (*batch_shape, *event_shape).

dtype property

The store's dtype — the value's, as a NumericArray's is.

ndim property

The rank of the store, batch axes included.

__repr__()

The summary of the label, the levels, and the elements' spec, then the stored entries.

Each line of the entries is indented by two spaces, as a record's lines are. NumPy's printing formats the stored array, batch axes leading, so np.set_printoptions sets the precision and shortens a large batch with ..., and only the entries shown are read from the device. Inside a JAX trace, where the store is a tracer, the repr is the summary alone.

Source code in probpipe/core/_numeric_array_batch.py
def __repr__(self) -> str:
    """The summary of the label, the levels, and the elements' spec, then the stored entries.

    Each line of the entries is indented by two spaces, as a record's lines
    are. NumPy's printing formats the stored array, batch axes leading, so
    ``np.set_printoptions`` sets the precision and shortens a large batch
    with ``...``, and only the entries shown are read from the device.
    Inside a JAX trace, where the store is a tracer, the repr is the summary
    alone.
    """
    return summary_with_values(self._repr_summary(), format_entries(self._values, VALUE_INDENT))

__str__()

The stored entries alone, as the repr shows them, or the summary inside a JAX trace.

Source code in probpipe/core/_numeric_array_batch.py
def __str__(self) -> str:
    """The stored entries alone, as the repr shows them, or the summary inside a JAX trace."""
    values = format_entries(self._values)
    return self._repr_summary() if values is None else values

as_jax()

The store as a jax.Array — the single conversion point.

A store already held as one passes through, tracers included; a native container converts through its registered backend. Concrete conversions are memoised; traced conversions stay within their transform.

Source code in probpipe/core/_numeric_array_batch.py
def as_jax(self) -> Any:
    """The store as a ``jax.Array`` — the single conversion point.

    A store already held as one passes through, tracers included; a native
    container converts through its registered backend. Concrete conversions
    are memoised; traced conversions stay within their transform.
    """
    if isinstance(self._values, jax.Array):
        return self._values
    cached = getattr(self, "_jax_cache", None)
    if cached is None:
        cached = _to_jax_array(self._values)
        if not isinstance(cached, jax.core.Tracer):
            object.__setattr__(self, "_jax_cache", cached)
    return cached

OpaqueBatch(elements, /, level_names, *, label, element=None, axes_per_level=None, provenance=None)

Bases: _ObjectBatch[Any]

A batch of opaque objects sharing one OpaqueSpec.

Parameters:

Name Type Description Default
elements ndarray or iterable

The objects, as an object array of any shape or a flat iterable.

required
level_names str or sequence of str

One name per level, outermost first.

required
label str

The batch's label. Required, as it is for every batch: a batch is a value a caller holds, and a label derived from its class says nothing about what it holds.

required
element OpaqueSpec

The spec every element satisfies. Defaults to the OpaqueSpec of the type the elements share exactly, which admits any value when they differ.

None
axes_per_level int or sequence of int

How many axes each level holds, outermost first (a single int is one level's count); they must account for every batch axis. Defaults to one axis per level, which requires as many names as there are batch axes. The sizes are read off the elements rather than restated here — they are already fixed by the data, so the only thing left to say is where one level ends and the next begins.

None
provenance Provenance

How this batch was produced.

None

Raises:

Type Description
TypeError

If element is not an OpaqueSpec; if an element is a mapping, naming the position that failed; if elements is a string, a mapping, or an array that is not dtype=object — each iterates into something other than its elements — or is not iterable at all.

ValueError

If elements is a zero-dimensional array (one object, with no batch axis to count along); if axes_per_level does not account for every axis the elements are stored in, or gives a count that is not one per level; or if it is omitted and the number of level names does not match the number of axes.

TypeError

If level_names is not a str or a sequence of str, or axes_per_level is not an int or a sequence of ints; a generator, a set, bytes, and a mapping are refused for both.

ValueError

If an axes_per_level count is less than 1, or a level name is empty or contains /.

Notes

An opaque value exposes no structure, so there is nothing to stack it into and the collection is a batch. An element may be any value except a mapping, which the value layer reads as a subtree rather than a leaf.

This is the case a batch's own spec exists for: an OpaqueSpec names no ProbPipe kind, yet the batch is specified all the same, at the family kind over it.

This batch stores its elements, and batch[i] is a view of the stored object: an Opaque holding it under the label derived from the position, or, for a stored tracked term, a copy of that term under the derived label that shares its representation. Its provenance records the batch and the stored term. A sub-batch is a view and takes a derived label as any view does.

Examples:

>>> batch = OpaqueBatch(
...     ["north", "south"],
...     "site",
...     label="labels",
... )
>>> batch.batch_shape
(2,)
>>> batch[0].raw
'north'
>>> batch[0].label
'labels[site=0]'
Source code in probpipe/core/_opaque_batch.py
def __init__(
    self,
    elements: np.ndarray | Iterable[Any],
    /,
    level_names: NamesLike,
    *,
    label: str,
    element: OpaqueSpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    super().__init__(
        elements,
        level_names,
        label=label,
        element=element,
        axes_per_level=axes_per_level,
        provenance=provenance,
    )

Designs

Design(fields, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)

Bases: RecordBatch

A batch of records that carries its per-field marginals.

A Design is not meant to be instantiated directly — concrete subclasses (FullFactorialDesign) assemble the underlying rows in __init__ and stash the originating marginals for introspection.

Two equivalent ways to drive a sweep through a @function::

@function
def fit(p): ...
result = fit(p=design)              # one row per call

@function
def fit(r, K): ...
result = fit(**design.select_all()) # zip across sibling views

select_all() returns one view per field; the views carry this Design's own design level, and the sweep layer zips arguments that share a level name (so the two shapes above produce identical outputs). For raw columns (no sweep — just JAX broadcasting), index with design["r"].

Attributes:

Name Type Description
marginals Mapping[str, Any]

The per-field marginals this design was built from, in construction (insertion) order. Kept for introspection; read-only.

Source code in probpipe/core/_record_batch.py
def __init__(
    self,
    fields: Mapping[str, Any],
    /,
    level_names: NamesLike,
    *,
    label: str | None = None,
    element: RecordSpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    kind = type(self).__name__
    names = _as_names(level_names, what=f"{kind} level_names")
    axes = (
        None
        if axes_per_level is None
        else _as_axis_counts(axes_per_level, what=f"{kind} axes_per_level")
    )
    if element is None:
        element = _inferred_element_term_spec(fields, _batch_axis_count(names, axes), kind=kind)
    spec = _record_element_term_spec(element, kind=kind)
    store = _leaf_keyed_columns(fields, spec, kind=kind)
    # Derived from the validated spec, so a path-keyed and a nested mapping of
    # the same columns read alike, as a ``Record``'s top-level fields do.
    label = _derived_record_name(spec.children) if label is None else label

    batch_shape = _batch_shape_of(store, spec, kind=kind)
    groups = _axis_groups_for(batch_shape, names, axes, kind=kind)
    type(self)._check_columns(store, spec, kind=kind)
    store = {
        path: _frozen_object_column(column) if _is_object_array(column) else _read_only(column)
        for path, column in store.items()
    }

    object.__setattr__(self, "_columns", store)
    self._init_batch(
        BatchSpec._from_groups(spec, groups, names),
        label=label,
        provenance=provenance,
    )

marginals property

Per-field marginals this design was built from.

FullFactorialDesign(**marginals)

Bases: Design

Cartesian product over all marginals — one row per combination.

Each marginal is a Python sequence (list, tuple, numpy / jax array). Numeric marginals become jnp.ndarray columns and categorical / string marginals become numpy.ndarray(dtype=object) columns. Row order is row-major over the marginals in insertion order — i.e., the last-listed marginal varies fastest.

Parameters:

Name Type Description Default
**marginals Sequence

Candidate values for each field. Must pass at least one marginal; each must be non-empty.

{}

Examples:

Cartesian grid of two numeric fields:

>>> ff = FullFactorialDesign(r=[1.5, 1.8], K=[60.0, 80.0])
>>> ff.batch_shape
(4,)
>>> tuple(ff.event_template.keys())
('r', 'K')

Mixed numeric / categorical marginals are supported — columns fall out as object-dtype arrays for the categorical fields:

>>> ff2 = FullFactorialDesign(method=['nutpie', 'pymc'], scale=[0.5, 1.0])
>>> ff2.batch_shape
(4,)
Source code in probpipe/record/design.py
def __init__(self, **marginals: Sequence) -> None:
    if not marginals:
        raise ValueError("FullFactorialDesign requires at least one marginal")
    names = list(marginals)
    lists = [list(marginals[n]) for n in names]
    sizes = [len(v) for v in lists]
    if any(s == 0 for s in sizes):
        raise ValueError(
            "FullFactorialDesign marginals must each be non-empty; "
            f"got sizes {dict(zip(names, sizes))}"
        )
    # ``meshgrid(..., indexing='ij')`` then flatten: each axis
    # iterates at its own stride; C-order flatten then yields a
    # lexicographic row-major traversal over the marginals in
    # insertion order.
    grids = np.meshgrid(
        *(np.arange(s) for s in sizes),
        indexing="ij",
    )
    flat_indices = {name: grid.reshape(-1) for name, grid in zip(names, grids)}

    fields: dict[str, Any] = {}
    template_spec: dict[str, Any] = {}
    for name, values in zip(names, lists):
        col, field_spec = _seq_to_column(
            values,
            indices=flat_indices[name],
        )
        fields[name] = col
        template_spec[name] = field_spec

    RecordBatch.__init__(
        self,
        fields,
        DESIGN_LEVEL,
        element=RecordSpec(template_spec),
        axes_per_level=(1,),
        label=f"FullFactorialDesign({','.join(names)})",
    )
    # The label is derived from the marginals, not user-typed.
    object.__setattr__(self, "_marginals", dict(marginals))

Weights

Weights(*, n=None, weights=None, log_weights=None)

Normalized probability weights over n items.

Weights stores log-unnormalized weights internally for numerical stability and provides lazy-cached access to normalized weights and log-weights.

It implements the JAX array protocol (__jax_array__), so a Weights object can be passed directly to any JAX operation that expects an array — it will automatically convert to its normalized weight vector.

Parameters:

Name Type Description Default
n int

Number of items. When provided alone (without weights or log_weights), creates uniform weights. When provided alongside an array, validates that the array length matches.

None
weights ArrayLike, Weights, or None

Non-negative weights. n is inferred from len(weights) if not given explicitly. A pre-built Weights object is accepted and adopted without re-validation. Mutually exclusive with log_weights.

None
log_weights ArrayLike, Weights, or None

Log-unnormalized weights. Preferred when weights span many orders of magnitude (e.g. importance sampling). n is inferred from len(log_weights) if not given explicitly. A pre-built Weights object is accepted and adopted without re-validation. Mutually exclusive with weights.

None

Examples:

Create from raw weights or log-weights:

>>> w = Weights(weights=jnp.array([1.0, 2.0, 1.0]))
>>> w = Weights(log_weights=jnp.array([-1.0, 0.0, -1.0]))

Create uniform weights:

>>> w = Weights(n=5)

Use as a JAX array — the normalized weights, so a sum is one:

>>> float(jnp.sum(w))
1.0

That is what lets a Weights be passed anywhere a weight array is expected, jax.random.choice(..., p=w) included, and used directly in an array expression::

jnp.einsum("n,n...->...", w, vals)   # weighted sum
w * values                           # element-wise product

Access different representations explicitly when needed::

w.normalized         # Array, shape (n,) — probabilities summing to 1
w.log_normalized     # Array — log-probabilities (always an array)
w.log_unnormalized   # Array | None — raw stored log-weights (None if uniform)
w.is_uniform         # bool — True when all items are equally weighted

Compute weighted statistics directly::

w.mean(values)                  # weighted mean along leading axis
w.variance(values)              # weighted variance
w.covariance(values)            # weighted covariance matrix
w.choice(key, shape=(10,))      # draw 10 weighted random indices

Passing to distribution constructors — a distribution constructor that accepts weights also accepts a pre-built Weights object, which is used as-is (no re-validation), so log-weights reach it as one::

w = Weights(log_weights=log_w)
EmpiricalDistribution(samples, weights=w, output_name="x")

JAX compatibility — Weights is registered as a JAX pytree whose single leaf is the normalized weight array, so it works transparently inside jax.jit, jax.vmap, jnp.sum, jnp.einsum, and other JAX operations.

Notes

Zero weights and -inf in log-space. When a weight array contains zeros (e.g. [0.0, 1.0, 0.0]), the internal log-representation stores -inf for those entries. All Weights operations handle this correctly:

  • normalized produces 0.0 for those items (via softmax).
  • log_normalized contains -inf entries (mathematically correct: log(0) = -inf).
  • effective_sample_size is unaffected (logsumexp handles -inf inputs).
  • choice never selects zero-weight items.

Code that consumes log_normalized directly should be aware that -inf values may be present.

Source code in probpipe/_weights.py
def __init__(
    self,
    *,
    n: int | None = None,
    weights: ArrayLike | Weights | None = None,
    log_weights: ArrayLike | Weights | None = None,
):
    # --- Fast path: adopt an existing Weights object ---
    source = None
    if isinstance(weights, Weights):
        if log_weights is not None:
            raise ValueError("pass either weights or log_weights, not both")
        source = weights
    elif isinstance(log_weights, Weights):
        if weights is not None:
            raise ValueError("pass either weights or log_weights, not both")
        source = log_weights

    if source is not None:
        if n is not None and source._n != n:
            raise ValueError(f"weights must hold {n} weights, one per item, got {source._n}")
        self._n = source._n
        self._log_weights = source._log_weights
        self._is_uniform = source._is_uniform
        self._cache = source._cache
        return

    # --- Build from raw inputs ---
    # Infer n from array length when not given explicitly.
    if n is None:
        if weights is not None:
            weights = _as_float_array(weights)
            if weights.ndim != 1 or weights.shape[0] == 0:
                raise ValueError("weights must be a non-empty 1-D array")
            n = weights.shape[0]
        elif log_weights is not None:
            log_weights = _as_float_array(log_weights)
            if log_weights.ndim != 1 or log_weights.shape[0] == 0:
                raise ValueError("log_weights must be a non-empty 1-D array")
            n = log_weights.shape[0]
        else:
            raise ValueError("Weights needs n, weights or log_weights")

    self._log_weights, self._is_uniform = _validate_to_log_weights(
        n,
        weights,
        log_weights=log_weights,
    )
    self._n = n

    self._cache: Array | None = None

n property

Number of items.

is_uniform property

True when all items are equally weighted.

normalized property

Normalized weights, shape (n,).

Cached after the first access outside a trace. A value computed while tracing belongs to that trace, so it is returned without being cached.

log_normalized property

Normalized log-weights, shape (n,).

Returns -log(n) for uniform weights, matching the behavior of normalized which always returns an array.

log_unnormalized property

Raw log-unnormalized weights as stored. None when uniform.

effective_sample_size property

Kish's effective sample size (ESS).

.. math::

n_{\mathrm{eff}} = \frac{1}{\sum_i w_i^2}

where :math:w_i are the normalized weights. For uniform weights this equals n exactly.

Computed in log-space for numerical stability:

.. math::

n_{\mathrm{eff}}
= \exp\!\bigl(-\log \sum_i \exp(2 \log w_i)\bigr)
= \exp\!\bigl(-\mathrm{logsumexp}(2\,\log\mathbf{w})\bigr)

Returns:

Type Description
Array

Scalar effective sample size (1 <= n_eff <= n).

shape property

Shape of the weight vector: (n,).

dtype property

Data type of the underlying log-weights array.

For uniform weights, returns JAX's current default float dtype.

uniform(n) staticmethod

Create uniform weights over n items.

Equivalent to Weights(n=n) but avoids keyword overhead in hot internal paths.

Source code in probpipe/_weights.py
@staticmethod
def uniform(n: int) -> Weights:
    """Create uniform weights over *n* items.

    Equivalent to ``Weights(n=n)`` but avoids keyword overhead in
    hot internal paths.
    """
    w = object.__new__(Weights)
    w._n = n
    w._log_weights = None
    w._is_uniform = True
    w._cache = None
    return w

__jax_array__()

Return normalized weights as a JAX array.

This allows Weights to be used directly in JAX operations (jnp.sum(w), jnp.einsum(..., w, ...), w * arr, etc.).

Source code in probpipe/_weights.py
def __jax_array__(self) -> Array:
    """Return normalized weights as a JAX array.

    This allows ``Weights`` to be used directly in JAX operations
    (``jnp.sum(w)``, ``jnp.einsum(..., w, ...)``, ``w * arr``, etc.).
    """
    return self.normalized

mean(values)

Compute weighted mean: sum_i w_i * values[i].

Source code in probpipe/_weights.py
def mean(self, values: Array) -> Array:
    """Compute weighted mean: ``sum_i w_i * values[i]``."""
    return weighted_mean(
        None if self._is_uniform else self.normalized,
        values,
    )

variance(values, mean=None)

Compute weighted variance over the leading axis.

Source code in probpipe/_weights.py
def variance(self, values: Array, mean: Array | None = None) -> Array:
    """Compute weighted variance over the leading axis."""
    return weighted_variance(
        None if self._is_uniform else self.normalized,
        values,
        mean=mean,
    )

covariance(values, mean=None)

Compute weighted covariance matrix over the leading axis.

Source code in probpipe/_weights.py
def covariance(self, values: Array, mean: Array | None = None) -> Array:
    """Compute weighted covariance matrix over the leading axis."""
    return weighted_covariance(
        None if self._is_uniform else self.normalized,
        values,
        mean=mean,
    )

choice(key, *, shape=())

Draw weighted random indices from 0..n-1, of shape shape.

Parameters:

Name Type Description Default
key PRNGKey

JAX PRNG key.

required
shape int or sequence of int

The shape of the index array. A single int is one axis, so shape=10 draws ten indices, and () draws one.

()

Returns:

Type Description
Array

Integer index array of shape shape.

Raises:

Type Description
TypeError

If shape is not an int or a sequence of ints, or a size is a bool.

ValueError

If a size is negative.

Source code in probpipe/_weights.py
def choice(self, key: PRNGKey, *, shape: SizesLike = ()) -> Array:
    """Draw weighted random indices from ``0..n-1``, of shape *shape*.

    Parameters
    ----------
    key : PRNGKey
        JAX PRNG key.
    shape : int or sequence of int
        The shape of the index array. A single int is one axis, so
        ``shape=10`` draws ten indices, and ``()`` draws one.

    Returns
    -------
    Array
        Integer index array of shape *shape*.

    Raises
    ------
    TypeError
        If *shape* is not an int or a sequence of ints, or a size is a ``bool``.
    ValueError
        If a size is negative.
    """
    return _weighted_choice(
        key,
        self._n,
        None if self._is_uniform else self.normalized,
        _as_shape(shape, what="Weights.choice shape", symbolic=False),
    )

subsample(indices)

Return a new Weights for a subset, re-normalized.

Parameters:

Name Type Description Default
indices Array

Integer indices selecting a subset of items.

required

Returns:

Type Description
Weights

New Weights over len(indices) items with weights proportional to the original weights at indices.

Source code in probpipe/_weights.py
def subsample(self, indices: Array) -> Weights:
    """Return a new ``Weights`` for a subset, re-normalized.

    Parameters
    ----------
    indices : Array
        Integer indices selecting a subset of items.

    Returns
    -------
    Weights
        New ``Weights`` over ``len(indices)`` items with weights
        proportional to the original weights at *indices*.
    """
    if self._is_uniform:
        return Weights.uniform(len(indices))
    sub_log = self._log_weights[indices]
    return Weights(log_weights=sub_log)

tree_flatten()

Flatten for JAX pytree.

The single leaf is the normalized weight array so that JAX operations (jnp.sum, jnp.einsum, etc.) receive a plain array when unpacking the pytree.

Source code in probpipe/_weights.py
def tree_flatten(self):
    """Flatten for JAX pytree.

    The single leaf is the **normalized** weight array so that JAX
    operations (``jnp.sum``, ``jnp.einsum``, etc.) receive a plain
    array when unpacking the pytree.
    """
    return (self.normalized,), (self._n, self._is_uniform)

tree_unflatten(aux, children) classmethod

Unflatten from JAX pytree.

Source code in probpipe/_weights.py
@classmethod
def tree_unflatten(cls, aux, children):
    """Unflatten from JAX pytree."""
    (normalized,) = children
    n, is_uniform = aux
    w = object.__new__(cls)
    w._n = n
    w._is_uniform = is_uniform
    if is_uniform:
        w._log_weights = None
    else:
        w._log_weights = jnp.log(jnp.clip(normalized, 1e-45))
    w._cache = normalized
    return w

Named trees

NamedTree

The named, ordered tree addressed by path — the shared collection substrate.

A NamedTree is a named, ordered collection of fields stored in a nested, tree-like structure: a field is one named leaf, and the leaf value is nameless on its own — the name the tree gives it makes it a field. A path is a str of /-joined names from the top of the tree down to a node, which is a field or a group, a node that is itself a tree. A child of a node is an entry directly under it, and the canonical order is the depth-first walk visiting children in insertion order. Sibling names are distinct, so every path identifies at most one node; distinct groups may reuse a name (a/c and b/c).

keys(), values(), items(), iteration, and len range over the fields, keyed by path in canonical order. [] takes a path or a list of paths:

  • one path, a str, gives the node there: a field's object, or the group's tree, so x["a"]["b/c"] == x["a/b/c"];
  • a list or a tuple of paths gives a tree of the same family cut down to those nodes, each at its own path and in this tree's canonical order, whatever order the paths are given in.

p in x is true when p is a str and x[p] gives a node, so it holds for a group, which keys() does not list. children is the one-level view of the storage, and at_path reaches the node at a path given as separate segments, so x.children["a"].children["b"] is the node that x.at_path("a", "b") and x["a/b"] address.

A child is an interior node if and only if it is an instance of the family's own node class (the hook _node_type); every other value is a leaf, validated against the family's declared _leaf_type at construction. The static counterpart of that leaf type is the class type parameter L — RecordSpec binds TermSpec, Record binds Any — which the leaf-trafficking accessors ([], values, items, map) carry through to typed consumers. Those accessors return each leaf as the family presents it (the hook _present), which is the stored leaf unless the family overrides the hook. Mappings are never leaves: a mapping value denotes tree structure (see _check_leaf). Navigation yields views into the same storage; the structure-preserving transforms (map, replace, __and__, without, rename) return a tree of the same family, rebuilt through _rebuild_class.

This substrate provides no constructor logic; each family's constructor owns storage (the _tree attribute) and validation policy.

fields property

Top-level field names, in insertion order — tuple(self.children).

Temporary, retained during the migration to the collection vocabulary; new code should use children (one-level mapping) or keys (leaf keys). It is scheduled for removal once that vocabulary is carried onto the distribution layer, and should not be relied on in new code.

children property

Read-only one-level view of this node — local_name -> child.

Each value is an immediate child: a field object (leaf) or a subtree (a nested collection of the same class). Insertion-ordered. This is the labelled top-level view; the top-level names are tuple(obj.children). Unlike the leaf-keyed field view, children.values() includes subtrees.

is_multi_field property

Whether this tree holds more than one field.

Counts reachable fields recursively (descending into nested subtrees), not top-level children — a single top-level child that nests several fields is multi-field. Equivalent to len(self) > 1.

keys()

The field keys (/-paths to the leaves), in canonical order.

Returns a reusable (materialised) tuple, matching the dict-like contract; iteration over the collection yields the same keys.

Source code in probpipe/core/named_tree.py
def keys(self) -> tuple[str, ...]:
    """The field keys (``/``-paths to the leaves), in canonical order.

    Returns a reusable (materialised) tuple, matching the dict-like
    contract; iteration over the collection yields the same keys.
    """
    return tuple(path for path, _ in self._walk_leaves())

values()

The field objects (one per leaf), in canonical order (materialised).

Source code in probpipe/core/named_tree.py
def values(self) -> tuple[L, ...]:
    """The field objects (one per leaf), in canonical order (materialised)."""
    return tuple(self._present(key, leaf) for key, leaf in self._walk_leaves())

items()

(key, field_object) pairs, in canonical order (materialised).

Source code in probpipe/core/named_tree.py
def items(self) -> tuple[tuple[str, L], ...]:
    """``(key, field_object)`` pairs, in canonical order (materialised)."""
    return tuple((key, self._present(key, leaf)) for key, leaf in self._walk_leaves())

__getitem__(paths)

The node at a path, or this tree cut down to the nodes at a list of paths.

A tuple is read as a list of paths; a nested path is written with /, so x["g/c"] is the node c inside the group g, while x["g", "c"] is the tree cut down to the top-level nodes g and c.

Parameters:

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

One path, which gives the node there, or a list of paths, which gives a tree of the same family holding each of those nodes at its own path, in this tree's canonical order.

required

Returns:

Type Description
L or Self

A field's object, a group's tree, or the cut-down tree.

Raises:

Type Description
KeyError

If a path is not a path of this tree.

TypeError

If paths is neither a string nor a list or tuple of strings.

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.

Source code in probpipe/core/named_tree.py
def __getitem__(self, paths: PathsLike, /) -> L | Self:
    """The node at a path, or this tree cut down to the nodes at a list of paths.

    A tuple is read as a list of paths; a nested path is written with ``/``, so
    ``x["g/c"]`` is the node ``c`` inside the group ``g``, while
    ``x["g", "c"]`` is the tree cut down to the top-level nodes ``g`` and
    ``c``.

    Parameters
    ----------
    paths : str, or list or tuple of str
        One path, which gives the node there, or a list of paths, which
        gives a tree of the same family holding each of those nodes at its
        own path, in this tree's canonical order.

    Returns
    -------
    L or Self
        A field's object, a group's tree, or the cut-down tree.

    Raises
    ------
    KeyError
        If a path is not a path of this tree.
    TypeError
        If *paths* is neither a string nor a list or tuple of strings.
    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.
    """
    read_paths = _as_paths(paths, action=f"index {type(self).__name__} by")
    if isinstance(read_paths, str):
        node = self._existing_node_at(read_paths)
        if isinstance(node, self._node_type()):
            return node
        # Past the node-type guard the value is a leaf; ``_node_type()`` is a
        # runtime ``type`` a checker cannot use to narrow the ``L | Self`` union.
        return self._present(read_paths, cast(L, node))
    tuple_given = read_paths if isinstance(paths, tuple) else ()
    for path in read_paths:
        self._existing_node_at(path, requested=tuple_given)
    return self._cut_to(read_paths)

__contains__(path)

Whether path is a str and a path of this tree, of a field or of a group.

Source code in probpipe/core/named_tree.py
def __contains__(self, path: object, /) -> bool:
    """Whether *path* is a ``str`` and a path of this tree, of a field or of a group."""
    if not isinstance(path, str):
        return False
    try:
        self._node_at(path)
    except KeyError:
        return False
    return True

at_path(*segments)

The node at the path that segments spell: a field's object, or a group's tree.

Each segment is a name or a path, and the segments are joined with /, so these are equivalent::

obj.at_path("physics/mass")
obj.at_path("physics", "mass")
obj["physics/mass"]

obj[path] is the recommended form; at_path reads the same node.

Parameters:

Name Type Description Default
*segments str

The path's segments, one per argument.

()

Returns:

Type Description
L or Self

The field's object, as the family presents it, or the group's tree.

Raises:

Type Description
KeyError

If the path is not a path of this tree.

TypeError

If a segment is not a string, such as a tuple of segments.

ValueError

If no segment is given, or the path has an empty name.

Source code in probpipe/core/named_tree.py
def at_path(self, *segments: str) -> L | Self:
    """The node at the path that *segments* spell: a field's object, or a group's tree.

    Each segment is a name or a path, and the segments are joined with
    ``/``, so these are equivalent::

        obj.at_path("physics/mass")
        obj.at_path("physics", "mass")
        obj["physics/mass"]

    ``obj[path]`` is the recommended form; ``at_path`` reads the same node.

    Parameters
    ----------
    *segments : str
        The path's segments, one per argument.

    Returns
    -------
    L or Self
        The field's object, as the family presents it, or the group's tree.

    Raises
    ------
    KeyError
        If the path is not a path of this tree.
    TypeError
        If a segment is not a string, such as a tuple of segments.
    ValueError
        If no segment is given, or the path has an empty name.
    """
    path = _as_joined_path(segments, function="at_path")
    node = self._existing_node_at(path)
    if isinstance(node, self._node_type()):
        return node
    return self._present(path, cast(L, node))

is_field(path)

Whether path is the path of a field of this tree, rather than of a group or of nothing.

Parameters:

Name Type Description Default
path str

One path.

required

Returns:

Type Description
bool

Whether a field is at path.

Raises:

Type Description
TypeError

If path is not a string.

ValueError

If path is empty or has an empty name.

Source code in probpipe/core/named_tree.py
def is_field(self, path: str) -> bool:
    """Whether *path* is the path of a field of this tree, rather than of a group or of nothing.

    Parameters
    ----------
    path : str
        One path.

    Returns
    -------
    bool
        Whether a field is at *path*.

    Raises
    ------
    TypeError
        If *path* is not a string.
    ValueError
        If *path* is empty or has an empty name.
    """
    path = _as_path(path, action="call is_field() with")
    try:
        node = self._node_at(path)
    except KeyError:
        return False
    return not isinstance(node, self._node_type())

to_nested_dict()

Return a nested dict mirroring the storage tree.

Each interior node becomes a nested dict; each leaf maps to its field object. This is the tree-shaped export, distinct from the flat dict(obj) view that is keyed by full path.

Source code in probpipe/core/named_tree.py
def to_nested_dict(self) -> dict[str, Any]:
    """Return a nested ``dict`` mirroring the storage tree.

    Each interior node becomes a nested ``dict``; each leaf maps to its
    field object. This is the tree-shaped export, distinct from the flat
    ``dict(obj)`` view that is keyed by full path.
    """
    node_type = self._node_type()
    result: dict[str, Any] = {}
    for name, child in self._tree.items():
        result[name] = child.to_nested_dict() if isinstance(child, node_type) else child
    return result

map(f, /, *args, **kwargs)

Apply f to every field object, returning a same-shape collection.

Returns a new collection of the same structure (identical names and nesting) whose fields are f's outputs, rebuilt through the class's constructor via _rebuild_class — for the value types this is the same class; a base RecordSpec may auto-promote to (or demote from) NumericRecordSpec when the mapped specs change numericness. f is called as f(field_object, *args, **kwargs) for each field in canonical order. Any extra args / kwargs are forwarded to f unchanged and are constant across fields (not varied per field).

The structure is preserved exactly. f must return a leaf object, not an instance of the node type (the class returned by _node_type); such a return would introduce nesting and raises ValueError naming the field. Each output is placed back through the subclass's own construction, so whatever normalisation that constructor applies to a leaf applies here too (see the concrete class's docstring).

Parameters:

Name Type Description Default
f callable

The function applied to each field object.

required
*args Any

Further positional arguments of f.

()
**kwargs Any

Further keyword arguments of f.

{}

Returns:

Type Description
Self

The collection of the outputs of f.

Raises:

Type Description
ValueError

If f returns a node-type instance at any field.

Source code in probpipe/core/named_tree.py
def map(self, f: Callable[..., L], /, *args: Any, **kwargs: Any) -> Self:
    """Apply *f* to every field object, returning a same-shape collection.

    Returns a new collection of the **same structure** (identical names and
    nesting) whose fields are ``f``'s outputs, rebuilt through the class's
    constructor via :meth:`_rebuild_class` — for the value types this is the
    same class; a base ``RecordSpec`` may auto-promote to (or demote
    from) :class:`NumericRecordSpec` when the mapped specs change
    numericness. *f* is
    called as ``f(field_object, *args, **kwargs)`` for each field in canonical
    order. Any extra *args* / *kwargs* are forwarded to *f* unchanged and are
    **constant across fields** (not varied per field).

    The structure is preserved exactly. *f* must return a leaf object, not an
    instance of the node type (the class returned by :meth:`_node_type`); such
    a return would introduce nesting and raises ``ValueError`` naming the
    field. Each output is placed back through the subclass's own construction,
    so whatever normalisation that constructor applies to a leaf applies here
    too (see the concrete class's docstring).

    Parameters
    ----------
    f : callable
        The function applied to each field object.
    *args : Any
        Further positional arguments of *f*.
    **kwargs : Any
        Further keyword arguments of *f*.

    Returns
    -------
    Self
        The collection of the outputs of *f*.

    Raises
    ------
    ValueError
        If *f* returns a node-type instance at any field.
    """
    return self._rebuild_from_leaves(
        f(leaf, *args, **kwargs) for _, leaf in self._walk_leaves()
    )

map_with_keys(f, /, *args, **kwargs)

Like map, but f also receives each field's key (path).

f is called as f(key, field_object, *args, **kwargs), where key is the field's full /-path. Everything else — structure preservation, the node-type-return guard, per-class result handling — matches map.

Source code in probpipe/core/named_tree.py
def map_with_keys(self, f: Callable[..., L], /, *args: Any, **kwargs: Any) -> Self:
    """Like :meth:`map`, but *f* also receives each field's key (path).

    *f* is called as ``f(key, field_object, *args, **kwargs)``, where *key* is
    the field's full ``/``-path. Everything else — structure preservation,
    the node-type-return guard, per-class result handling — matches :meth:`map`.
    """
    return self._rebuild_from_leaves(
        f(key, leaf, *args, **kwargs) for key, leaf in self._walk_leaves()
    )

without(*paths)

Return a new collection with the fields and groups at paths removed.

Each path names a field, which is dropped, or a group, which is dropped with every node below it. Surviving fields keep their order and their specs, so a list of paths and without partition the fields.

Parameters:

Name Type Description Default
*paths str

One path per argument.

()

Returns:

Type Description
Self

The collection without those nodes.

Raises:

Type Description
KeyError

If a path is not a path of this tree.

TypeError

If a path is not a string, such as a tuple of paths.

ValueError

If a path is empty or has an empty name, the paths name a path twice or a path inside another, or every field would be removed.

Source code in probpipe/core/named_tree.py
def without(self, *paths: str) -> Self:
    """Return a new collection with the fields and groups at *paths* removed.

    Each path names a field, which is dropped, or a group, which is dropped
    with every node below it. Surviving fields keep their order and their
    specs, so a list of paths and ``without`` partition the fields.

    Parameters
    ----------
    *paths : str
        One path per argument.

    Returns
    -------
    Self
        The collection without those nodes.

    Raises
    ------
    KeyError
        If a path is not a path of this tree.
    TypeError
        If a path is not a string, such as a tuple of paths.
    ValueError
        If a path is empty or has an empty name, the paths name a path
        twice or a path inside another, or every field would be removed.
    """
    paths = _as_path_arguments(paths, action="call without() with")
    return self._rebuild_node(self._leaves_without(paths), node_name=None)

__and__(other)

Merge two trees by top-level name: this tree's fields and groups, then other's.

The merge is shallow: a top-level name, a field or a group, present in both trees raises, even when the two groups hold different fields. To merge two groups of one name, merge the groups first and put the result under the name.

Parameters:

Name Type Description Default
other NamedTree

The tree whose fields and groups are added.

required

Returns:

Type Description
Self

Both trees' fields and groups side by side.

Raises:

Type Description
TypeError

If other is not a tree of this family, through NotImplemented.

ValueError

If a top-level name is in both trees.

Examples:

>>> from probpipe import RecordSpec
>>> (RecordSpec(a=(3,)) & (RecordSpec(g=RecordSpec(b=()))))
NumericRecordSpec(a=(3,), g=NumericRecordSpec(b=()))
Source code in probpipe/core/named_tree.py
def __and__(self, other: Any) -> Self:
    """Merge two trees by top-level name: this tree's fields and groups, then *other*'s.

    The merge is shallow: a top-level name, a field or a group, present in
    both trees raises, even when the two groups hold different fields. To
    merge two groups of one name, merge the groups first and put the result
    under the name.

    Parameters
    ----------
    other : NamedTree
        The tree whose fields and groups are added.

    Returns
    -------
    Self
        Both trees' fields and groups side by side.

    Raises
    ------
    TypeError
        If *other* is not a tree of this family, through ``NotImplemented``.
    ValueError
        If a top-level name is in both trees.

    Examples
    --------
    >>> from probpipe import RecordSpec
    >>> (RecordSpec(a=(3,)) & (RecordSpec(g=RecordSpec(b=()))))
    NumericRecordSpec(a=(3,), g=NumericRecordSpec(b=()))
    """
    if not isinstance(other, self._node_type()):
        return NotImplemented
    return self._rebuild_node(self._leaves_merged(other), node_name=None)

replace(_updates=None, /, **updates)

Return a new collection with the objects at the given paths replaced.

Updates are given as a path-keyed positional mapping (r.replace({"physics/mass": m})) or flat keywords (r.replace(obs=y)), not both. Every path must already exist (KeyError otherwise — replace edits, it does not add). A partial path replaces a whole subtree. Untouched fields keep their specs; a replaced field takes the new value's spec.

Source code in probpipe/core/named_tree.py
def replace(self, _updates: Mapping[str, Any] | None = None, /, **updates: Any) -> Self:
    """Return a new collection with the objects at the given paths replaced.

    Updates are given as a path-keyed positional mapping
    (``r.replace({"physics/mass": m})``) or flat keywords (``r.replace(obs=y)``),
    not both. Every path must already exist (``KeyError`` otherwise — ``replace``
    edits, it does not add). A partial path replaces a whole subtree. Untouched
    fields keep their specs; a replaced field takes the new value's spec.
    """
    resolved = self._resolve_replace_updates(_updates, updates)
    if not resolved:
        return self
    return self._rebuild_node(self._leaves_replaced(resolved), node_name=None)

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

Return a same-family tree with the given nodes renamed or moved, old -> new.

Acts on the nodes within the tree, leaves or whole subtrees; the object itself is relabeled by with_label on the tracked value types. Each key is the exact path of a node, so a keyword addresses a top-level node and the positional renames any node. Each target is the node's new exact path, so a bare name is a top-level path::

t.rename(mu="loc")                  # rename a top-level node
t.rename({"g/mu": "g/loc"})         # rename a node within g
t.rename({"g/mu": "mu"})            # move it out of g
t.rename({"mu": "g/mu"})            # move it into g

The renames apply simultaneously: every key is resolved against the original tree, so swaps are well-defined, and a node below a moved node moves with it unless it has a target of its own. A node whose target has its source's parent, and none of whose ancestors moves, is renamed in place and keeps its position. Every other node is moved: it is appended at the end of its new parent's children, in the order the renames are given, and a missing parent is created and appended the same way. A group that the moves leave without a field is removed. The leaf objects are unchanged, and the mapping interface stays keyed by full path.

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 top-level node, keyed by the node's name.

{}

Returns:

Type Description
Self

A tree of the same family over the same leaf objects.

Raises:

Type Description
KeyError

If a key is not the path of a node.

TypeError

If a key or a target is not a string, such as a tuple of names.

ValueError

If a key or a target is empty or has an empty name, two keys rename the same node, no renames are given, a node moves into its own subtree, two targets are equal or one lies inside the other, or a target collides with a node that remains.

Source code in probpipe/core/named_tree.py
def rename(self, renames: Mapping[str, str] | None = None, /, **keyword_renames: str) -> Self:
    """Return a same-family tree with the given nodes renamed or moved, ``old -> new``.

    Acts on the nodes *within* the tree, leaves or whole subtrees; the object
    itself is relabeled by ``with_label`` on the tracked value types. Each key is
    the exact path of a node, so a keyword addresses a top-level node and the
    positional *renames* any node. Each target is the node's new exact path,
    so a bare name is a top-level path::

        t.rename(mu="loc")                  # rename a top-level node
        t.rename({"g/mu": "g/loc"})         # rename a node within g
        t.rename({"g/mu": "mu"})            # move it out of g
        t.rename({"mu": "g/mu"})            # move it into g

    The renames apply simultaneously: every key is resolved against the
    original tree, so swaps are well-defined, and a node below a moved node
    moves with it unless it has a target of its own. A node whose target has
    its source's parent, and none of whose ancestors moves, is renamed in
    place and keeps its position. Every other node is moved: it is appended
    at the end of its new parent's children, in the order the renames are
    given, and a missing parent is created and appended the same way. A group
    that the moves leave without a field is removed. The leaf objects are
    unchanged, and the mapping interface stays keyed by full path.

    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 top-level node, keyed by the node's name.

    Returns
    -------
    Self
        A tree of the same family over the same leaf objects.

    Raises
    ------
    KeyError
        If a key is not the path of a node.
    TypeError
        If a key or a target is not a string, such as a tuple of names.
    ValueError
        If a key or a target is empty or has an empty name, two keys rename
        the same node, no renames are given, a node moves into its own
        subtree, two targets are equal or one lies inside the other, or a
        target collides with a node that remains.
    """
    tree, _ = self._renamed_tree(self._resolve_path_renames(renames, keyword_renames))
    return self._rebuild_node(tree, node_name=None)

Linear operators

MultivariateNormal accepts a linear operator as its cov, and the _cov method of a family that claims SupportsCovariance returns one.

probpipe.linalg.LinOp()

Bases: ABC

Abstract base class for a linear operator.

Concrete subclasses must provide shape, dtype, matvec, rmatvec, and to_dense. LinOp provides convenience arithmetic (matmul, add, mul, ...) that constructs composed operators without densifying where possible. The matvec/rmatvec and matmat/rmatmat methods provide the option to implement matrix-vector and matrix-matrix products without densifying the operator.

Flags are restricted to ALLOWED_FLAGS. Use .flags (frozenset) to inspect.

Attributes: _flags: a set of semantic flags (e.g., "symmetric", "positive_definite"). See add_flag, has_flag.

Source code in probpipe/linalg/linear_operator.py
def __init__(self) -> None:
    self._flags: set[str] = set()

shape abstractmethod property

Return (n_out, n_in).

dtype abstractmethod property

Return the dtype of this operator's elements.

raw abstractmethod property

The stored parameterization, such as a dense operator's matrix or a lazy composite's operands.

is_dense property

Default is False; DenseLinOp overrides to True

flags property

Return frozenset of current flags (read-only view).

T property

Return a transposed operator view.

__init_subclass__(**kwargs)

Refuse a subclass on which raw is anything but a property.

Parameters:

Name Type Description Default
**kwargs Any

The class keywords, passed on to the next class in the MRO.

{}

Raises:

Type Description
TypeError

If raw on the class is anything but a property.

Source code in probpipe/linalg/linear_operator.py
def __init_subclass__(cls, **kwargs: Any) -> None:
    """Refuse a subclass on which ``raw`` is anything but a property.

    Parameters
    ----------
    **kwargs : Any
        The class keywords, passed on to the next class in the MRO.

    Raises
    ------
    TypeError
        If ``raw`` on the class is anything but a property.
    """
    super().__init_subclass__(**kwargs)
    _check_raw_is_a_property(cls)

to_dense() abstractmethod

Return dense array representation of the operator.

Implementations may raise if dense form is unaffordable.

Source code in probpipe/linalg/linear_operator.py
@abstractmethod
def to_dense(self) -> Array:
    """Return dense array representation of the operator.

    Implementations may raise if dense form is unaffordable.
    """
    ...

apply(x)

Apply the operator action, exactly as matvec.

Source code in probpipe/linalg/linear_operator.py
def apply(self, x: ArrayLike) -> Array:
    """Apply the operator action, exactly as :meth:`matvec`."""
    return self.matvec(x)

matvec(x)

Return A @ x for x shape (n_in,) -> (n_out,).

Source code in probpipe/linalg/linear_operator.py
def matvec(self, x: ArrayLike) -> Array:
    """Return A @ x for x shape (n_in,) -> (n_out,)."""
    x = _ensure_vector(x, name="x")
    return self.to_dense() @ x

rmatvec(x)

Return A^T @ x for x shape (n_out,) -> (n_in,).

Source code in probpipe/linalg/linear_operator.py
def rmatvec(self, x: ArrayLike) -> Array:
    """Return A^T @ x for x shape (n_out,) -> (n_in,)."""
    x = _ensure_vector(x, name="x")
    return self.to_dense().T @ x

matmat(X)

Return A @ X for X shape (n_in, k) or (n_in,)

Source code in probpipe/linalg/linear_operator.py
def matmat(self, X: ArrayLike) -> Array:
    """Return A @ X for X shape (n_in, k) or (n_in,)"""
    X = _ensure_matrix(X, name="X")
    return self.to_dense() @ X

rmatmat(X)

Return A.T @ X for X shape (n_out, k) or (n_out,)

Source code in probpipe/linalg/linear_operator.py
def rmatmat(self, X: ArrayLike) -> Array:
    """Return A.T @ X for X shape (n_out, k) or (n_out,)"""
    X = _ensure_matrix(X, name="X")
    return self.to_dense().T @ X

solve(b, **kwargs)

Solve A x = b; default uses dense fallback.

Source code in probpipe/linalg/linear_operator.py
def solve(self, b: ArrayLike, **kwargs) -> Array:
    """Solve A x = b; default uses dense fallback."""
    self._check_square()
    n, _ = self.shape
    dense_op = self.to_dense()

    b = jnp.asarray(b)
    if b.ndim < 2:
        b = _ensure_vector(b, name="b", as_column=True)
    b = _ensure_matrix(b, name="b", num_rows=n)

    return jnp.linalg.solve(dense_op, b)

cholesky(lower=True, **kwargs)

Return triangular LinOp L (lower) or L.T (upper) such that A = L @ L.T.

Defaults to densifying the operator and then computing the Cholesky decomposition. Subclasses may return other valid LinOp types that are more structured than TriangularLinOp; for example, DiagonalLinOp.

Source code in probpipe/linalg/linear_operator.py
def cholesky(self, lower: bool = True, **kwargs) -> CholeskyFactor:
    """Return triangular LinOp L (lower) or L.T (upper) such that A = L @ L.T.

    Defaults to densifying the operator and then computing the Cholesky decomposition.
    Subclasses may return other valid LinOp types that are more structured than
    TriangularLinOp; for example, DiagonalLinOp.
    """
    self._check_square()
    L = jnp.linalg.cholesky(self.to_dense())
    if not lower:
        L = L.T
    return TriangularLinOp(L, lower=lower)

to_cholesky_representation(lower=True, **kwargs)

Return representation of self in terms of its Cholesky factor.

In general, this represents an alternative represetation of the operator. Defaults to computing the Cholesky factor and wrapping the result in CholeskyLinOp. Subclasses may return other valid LinOp types when more structure is present; for example, DiagonalRootLinOp.

Source code in probpipe/linalg/linear_operator.py
def to_cholesky_representation(self, lower: bool = True, **kwargs) -> CholeskyRepresentation:
    """Return representation of `self` in terms of its Cholesky factor.

    In general, this represents an alternative represetation of the
    operator. Defaults to computing the Cholesky factor and wrapping
    the result in CholeskyLinOp. Subclasses may return other valid
    LinOp types when more structure is present; for example,
    DiagonalRootLinOp.
    """
    return CholeskyLinOp(self.cholesky(lower=lower, **kwargs))

diag()

Return diagonal of operator; default uses dense fallback.

Source code in probpipe/linalg/linear_operator.py
def diag(self) -> Array:
    """Return diagonal of operator; default uses dense fallback."""
    A = self.to_dense()
    return jnp.diag(A)

logdet()

Return log determinant; default uses dense fallback. Raises if sign <= 0

Source code in probpipe/linalg/linear_operator.py
def logdet(self) -> float:
    """Return log determinant; default uses dense fallback. Raises if sign <= 0"""
    self._check_square()
    A = self.to_dense()
    sign, log_det = jnp.linalg.slogdet(A)
    if sign <= 0:
        raise LinAlgError("cannot compute the log-determinant: the determinant is not positive")
    return float(log_det)

trace()

Return trace of operator; default uses dense fallback.

Source code in probpipe/linalg/linear_operator.py
def trace(self) -> float:
    """Return trace of operator; default uses dense fallback."""
    self._check_square()
    return float(jnp.trace(self.to_dense()))

add_flag(flag)

Attach a semantic flag (must be one of ALLOWED_FLAGS).

Source code in probpipe/linalg/linear_operator.py
def add_flag(self, flag: str) -> None:
    """Attach a semantic flag (must be one of ALLOWED_FLAGS)."""
    if flag not in ALLOWED_FLAGS:
        raise ValueError(unknown_names("flag", [flag], sorted(ALLOWED_FLAGS)))
    self._flags.add(flag)

remove_flag(flag)

Remove an attached flag (no-op if missing).

Source code in probpipe/linalg/linear_operator.py
def remove_flag(self, flag: str) -> None:
    """Remove an attached flag (no-op if missing)."""
    self._flags.discard(flag)

has_flag(flag)

Return True if flag attached.

Source code in probpipe/linalg/linear_operator.py
def has_flag(self, flag: str) -> bool:
    """Return True if flag attached."""
    return flag in self._flags

__matmul__(other)

Return operator representing self @ other (composition).

Source code in probpipe/linalg/linear_operator.py
def __matmul__(self, other: LinOp) -> LinOp:
    """Return operator representing self @ other (composition)."""
    return ProductLinOp(self, other)

__repr__()

The class, the shape and the dtype, and a composite's operands.

Source code in probpipe/linalg/linear_operator.py
def __repr__(self) -> str:
    """The class, the shape and the dtype, and a composite's operands."""
    fields = [("shape", repr(self.shape)), ("dtype", format_dtype(self.dtype))]
    return term_repr(type(self).__name__, None, [*fields, *self._operand_repr_arguments()])

probpipe.linalg.DenseLinOp(arr, copy=True)

Bases: LinOp

A light wrapper around a two dimensional array.

A LinearOperator that is represented by storing the complete dense array representation of the operator.

Source code in probpipe/linalg/linear_operator.py
def __init__(self, arr: ArrayLike, copy: bool = True) -> None:
    super().__init__()
    self.array = _ensure_matrix(arr, name="arr", copy=copy)
    self._dtype = self.array.dtype
    self.add_flag("dense")

raw property

The stored matrix.

probpipe.linalg.DiagonalLinOp(diag, copy=True)

Bases: LinOp

Diagonal operator represented by a 1D array of diagonal entries.

Parameters:

Name Type Description Default
diag array - like

The diagonal entries. An array of higher rank is flattened.

required
copy bool

Whether to store a copy of the flattened entries.

True
Source code in probpipe/linalg/linear_operator.py
def __init__(self, diag: ArrayLike, copy: bool = True) -> None:
    super().__init__()
    self.diagonal = _ensure_vector(jnp.asarray(diag).ravel(), copy=copy, name="diag")
    self._n = int(self.diagonal.size)
    self._dtype = self.diagonal.dtype

    self.add_flag("diagonal")
    self.add_flag("symmetric")
    if jnp.all(self.diagonal > 0):
        self.add_flag("positive_definite")

raw property

The stored diagonal.

solve(b, **kwargs)

For consistency with jnp.linalg.solve(), b can be (n,) or (n,k).

Source code in probpipe/linalg/linear_operator.py
def solve(self, b: ArrayLike, **kwargs) -> Array:
    """
    For consistency with jnp.linalg.solve(), b can be (n,) or (n,k).
    """
    if jnp.any(self.diagonal == 0):
        raise LinAlgError(
            "cannot solve with a diagonal operator whose diagonal has zero entries"
        )

    b = jnp.asarray(b)
    if b.ndim < 2:
        b = _ensure_vector(b, name="b", as_column=True)
    b = _ensure_matrix(b, name="b", num_rows=self._n)

    return b / self.diagonal[:, None]

cholesky(lower=True, **kwargs)

Note that lower has no effect on Cholesky decomposition of diagonal matrix

Source code in probpipe/linalg/linear_operator.py
def cholesky(self, lower: bool = True, **kwargs) -> DiagonalLinOp:
    """Note that `lower` has no effect on Cholesky decomposition of diagonal matrix"""
    if jnp.any(self.diagonal <= 0):
        raise LinAlgError(
            "cannot take the Cholesky factor: the diagonal has non-positive entries"
        )
    return DiagonalLinOp(jnp.sqrt(self.diagonal))

probpipe.linalg.TriangularLinOp(tri, *, lower=True, copy=True)

Bases: LinOp

Triangular operator represented by lower or upper triangular matrix L (2D array).

The operator interprets stored matrix tri so that: - if lower==True: stored tri is lower triangular and operator is L @ x - if lower==False: stored tri is upper triangular and operator is U @ x

Source code in probpipe/linalg/linear_operator.py
def __init__(self, tri: Array, *, lower: bool = True, copy: bool = True) -> None:
    super().__init__()
    tri = _ensure_square_matrix(tri, name="tri", copy=copy)
    self.tri = tri
    self.lower = bool(lower)
    self._n = self.tri.shape[0]
    self._dtype = self.tri.dtype

    if self.lower:
        self.add_flag("triangular_lower")
    else:
        self.add_flag("triangular_upper")
    # if strictly triangular with ones on diagonal, mark unit_diagonal
    if jnp.allclose(jnp.diag(self.tri), 1.0):
        self.add_flag("unit_diagonal")

raw property

The stored triangular matrix; its flags state which triangle it is.

solve(b, *, unit_diagonal=False, **kwargs)

Solve triangular system Lx=b or Ux=b.

Source code in probpipe/linalg/linear_operator.py
def solve(self, b: ArrayLike, *, unit_diagonal: bool = False, **kwargs) -> Array:
    """Solve triangular system Lx=b or Ux=b."""
    b_arr = jnp.asarray(b)
    if b_arr.ndim < 2:
        b_arr = _ensure_vector(b_arr, name="b", as_column=True)
    b_arr = _ensure_matrix(b_arr, name="b", num_rows=self._n)

    return jsla.solve_triangular(
        self.tri,
        b_arr,
        lower=self.lower,
        unit_diagonal=unit_diagonal,
    )

probpipe.linalg.CholeskyLinOp(root)

Bases: RootLinOp

Positive-definite operator represented by a Cholesky factor.

A lower root L represents A = L @ L.T; an upper root U represents A = U.T @ U.

Source code in probpipe/linalg/linear_operator.py
def __init__(self, root: TriangularLinOp) -> None:
    if not isinstance(root, TriangularLinOp):
        raise ValueError(
            f"CholeskyLinOp requires root to be a TriangularLinOp, got {type(root).__name__}"
        )

    super().__init__(root)
    self.add_flag("positive_definite")

raw property

The stored Cholesky factor, L of A = L @ L.T or U of A = U.T @ U.

matvec(x)

Return A @ x for the represented SPD operator.

Source code in probpipe/linalg/linear_operator.py
def matvec(self, x: ArrayLike) -> Array:
    """Return ``A @ x`` for the represented SPD operator."""
    if self.root.lower:
        return self.root.matvec(self.root.rmatvec(x))
    return self.root.rmatvec(self.root.matvec(x))

rmatvec(x)

Return A.T @ x; equal to A @ x for this symmetric operator.

Source code in probpipe/linalg/linear_operator.py
def rmatvec(self, x: ArrayLike) -> Array:
    """Return ``A.T @ x``; equal to ``A @ x`` for this symmetric operator."""
    return self.matvec(x)

matmat(X)

Return A @ X without densifying the Cholesky factor.

Source code in probpipe/linalg/linear_operator.py
def matmat(self, X: ArrayLike) -> Array:
    """Return ``A @ X`` without densifying the Cholesky factor."""
    if self.root.lower:
        return self.root.matmat(self.root.rmatmat(X))
    return self.root.rmatmat(self.root.matmat(X))

rmatmat(X)

Return A.T @ X; equal to A @ X for this symmetric operator.

Source code in probpipe/linalg/linear_operator.py
def rmatmat(self, X: ArrayLike) -> Array:
    """Return ``A.T @ X``; equal to ``A @ X`` for this symmetric operator."""
    return self.matmat(X)

diag()

Return the diagonal of the represented SPD operator.

Source code in probpipe/linalg/linear_operator.py
def diag(self) -> Array:
    """Return the diagonal of the represented SPD operator."""
    S = self.root.to_dense()
    axis = 1 if self.root.lower else 0
    return jnp.sum(S**2, axis=axis)

to_dense()

Return the dense matrix represented by the Cholesky factor.

Source code in probpipe/linalg/linear_operator.py
def to_dense(self) -> Array:
    """Return the dense matrix represented by the Cholesky factor."""
    S = self.root.to_dense()
    if self.root.lower:
        return S @ S.T
    return S.T @ S

solve(b, **kwargs)

Linear solve using forward backward triangular substitution

For lower roots, compute A^{-1} b = (L @ L.T)^{-1} b by solving through L and then L.T. For upper roots, compute A^{-1} b = (U.T @ U)^{-1} b by solving through U.T and then U.

Source code in probpipe/linalg/linear_operator.py
def solve(self, b: ArrayLike, **kwargs) -> Array:
    """Linear solve using forward backward triangular substitution

    For lower roots, compute ``A^{-1} b = (L @ L.T)^{-1} b`` by
    solving through ``L`` and then ``L.T``. For upper roots, compute
    ``A^{-1} b = (U.T @ U)^{-1} b`` by solving through ``U.T`` and
    then ``U``.
    """
    b = jnp.asarray(b)
    if b.ndim < 2:
        b = _ensure_vector(b, name="b", as_column=True)
    b = _ensure_matrix(b, name="b", num_rows=self._n)

    S = self.root.to_dense()
    if self.root.lower:
        y = jsla.solve_triangular(S, b, lower=True)
        return jsla.solve_triangular(S.T, y, lower=False)
    y = jsla.solve_triangular(S.T, b, lower=True)
    return jsla.solve_triangular(S, y, lower=False)

to_cholesky_representation(lower=True, **kwargs)

Returns a copy of self

Source code in probpipe/linalg/linear_operator.py
def to_cholesky_representation(self, lower: bool = True, **kwargs) -> CholeskyLinOp:
    """Returns a copy of `self`"""
    return CholeskyLinOp(self.cholesky(lower=lower))

probpipe.linalg.RootLinOp(root)

Bases: LinOp

A positive-semidefinite operator A = S @ S.T, stored as its root S.

A linear operator A represented by its square root S such that A = S @ S.T A is guaranteed to be symmetric positive semidefinite, but not necessarily positive definite.

Source code in probpipe/linalg/linear_operator.py
def __init__(self, root: LinOp | ArrayLike) -> None:
    super().__init__()
    self.root = _as_linear_operator(root)
    self._n = self.root.shape[0]
    self.add_flag("symmetric")

raw property

The stored root S of A = S @ S.T, an operator.

solve(b, **kwargs)

Linear solve using forward backward substitution

To compute A^{-1}b = (S @ S.T)^{-1}b first compute y = S^{-1}b then S.T^{-1}y.

Source code in probpipe/linalg/linear_operator.py
def solve(self, b: ArrayLike, **kwargs) -> Array:
    """Linear solve using forward backward substitution

    To compute A^{-1}b = (S @ S.T)^{-1}b first compute y = S^{-1}b
    then S.T^{-1}y.
    """
    b = jnp.asarray(b)
    if b.ndim < 2:
        b = _ensure_vector(b, name="b", as_column=True)
    b = _ensure_matrix(b, name="b", num_rows=self._n)

    S = self.root.to_dense()
    y = jnp.linalg.solve(S, b)
    return jnp.linalg.solve(S.T, y)

probpipe.linalg.DiagonalRootLinOp(root)

Bases: DiagonalLinOp

A diagonal operator A = S @ S.T, stored as its diagonal root S.

A linear operator A represented by its diagonal square root S = diag(s1, ..., sd) such that A = S @ S.T = diag(s1^2, ..., sd^2). A is guaranteed to be symmetric positive semidefinite, and is strictly positive definite if all entries of all of the si are non-zero.

Source code in probpipe/linalg/linear_operator.py
def __init__(self, root: DiagonalLinOp) -> None:
    if not isinstance(root, DiagonalLinOp):
        raise ValueError(
            f"DiagonalRootLinOp requires root to be a DiagonalLinOp, got {type(root).__name__}"
        )

    # Call DiagonalLinOp constructor
    super().__init__(root.diagonal**2)
    self.root = root

raw property

The stored diagonal root S of A = S @ S.T, an operator.

cholesky(lower=True, **kwargs)

Note that lower has no effect on Cholesky decomposition of diagonal matrix

Source code in probpipe/linalg/linear_operator.py
def cholesky(self, lower: bool = True, **kwargs) -> DiagonalLinOp:
    """Note that `lower` has no effect on Cholesky decomposition of diagonal matrix"""
    if jnp.any(self.diagonal <= 0):
        raise LinAlgError(
            "cannot take the Cholesky factor: the diagonal has non-positive entries"
        )
    return DiagonalLinOp(self.root.diagonal)