Skip to content

API Reference — Composition Core

The Operator / Sequential / Graph composition algebra lives in the carrier-agnostic pipekit framework and is re-exported at geotoolz.* (and pipekit.*) for convenience. The only geotoolz-specific addition on this page is ModelOp, which lives at geoops.learn.

For the model behind these primitives, read the Concepts page first.

Base

pipekit_ops.Operator

Bases: ConfigMixin

Base class for pipekit operators.

Subclasses implement _apply(self, *args, **kwargs). The base class dispatches __call__ to either _apply (eager) or Node construction (symbolic) based on whether any positional argument is a graph node.

Attributes:

Name Type Description
forbid_in_yaml bool

True on subclasses that directly hold non-serialisable user state (callables, closures, runtime arrays, RNGs). YAML loaders and from_state refuse to instantiate flagged operators; check_pickleable surfaces them as pickleability warnings. Operators that only nest other operators leave this False — the walker finds flagged children structurally. Default False.

_terminal bool

True on subclasses that legitimately return None (or otherwise break the carrier-in / carrier-out contract). Sequential rejects terminal operators except as the last step. Default False.

backends tuple[str, ...] | None

The array backends the operator runs on ("numpy", "jax", "dask"), or None (the default) for an operator that does not care. When set, NumPy and JAX inputs go where the operator runs: NumPy joins JAX if it lists "jax"; otherwise JAX data goes to the host, and the result comes back as JAX. pipekit_ops.guard reports each move. An input on any other backend, a mix with dask, or a traced input of an operator without "jax" raises pipekit_ops.carriers.BackendError before _apply runs. Values with no backend (numbers, strings, tables) stay as they are.

traceable bool

False on an operator that must not run inside jax.jit: it stores what it computes, or acts on the world. pipekit_ops.jit_report reads it; nothing else does. Default True.

Example

Define and compose::

class Scale(Operator):
    def __init__(self, factor: float) -> None:
        self.factor = factor

    def _apply(self, x):
        return x * self.factor

pipe = Scale(0.5) | Scale(2.0)   # Sequential([Scale(0.5), Scale(2.0)])
assert pipe(10.0) == 10.0
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
class Operator(ConfigMixin):
    """Base class for pipekit operators.

    Subclasses implement ``_apply(self, *args, **kwargs)``. The base
    class dispatches ``__call__`` to either ``_apply`` (eager) or
    `Node` construction (symbolic) based on whether any positional
    argument is a graph node.

    Attributes:
        forbid_in_yaml: ``True`` on subclasses that *directly* hold
            non-serialisable user state (callables, closures, runtime
            arrays, RNGs). YAML loaders and `from_state` refuse to
            instantiate flagged operators; `check_pickleable`
            surfaces them as pickleability warnings. Operators that only
            nest other operators leave this ``False`` — the walker finds
            flagged children structurally. Default ``False``.
        _terminal: ``True`` on subclasses that legitimately return
            ``None`` (or otherwise break the carrier-in / carrier-out
            contract). `Sequential` rejects terminal operators except
            as the last step. Default ``False``.
        backends: The array backends the operator runs on (``"numpy"``,
            ``"jax"``, ``"dask"``), or ``None`` (the default) for an
            operator that does not care. When set, NumPy and JAX inputs
            go where the operator runs: NumPy joins JAX if it lists
            ``"jax"``; otherwise JAX data goes to the host, and the result
            comes back as JAX. `pipekit_ops.guard` reports each move. An
            input on any other backend, a mix with dask, or a traced input
            of an operator without ``"jax"`` raises
            `pipekit_ops.carriers.BackendError` before ``_apply`` runs.
            Values with no backend (numbers, strings, tables) stay as they
            are.
        traceable: ``False`` on an operator that must not run inside
            ``jax.jit``: it stores what it computes, or acts on the world.
            `pipekit_ops.jit_report` reads it; nothing else does. Default
            ``True``.

    Example:
        Define and compose::

            class Scale(Operator):
                def __init__(self, factor: float) -> None:
                    self.factor = factor

                def _apply(self, x):
                    return x * self.factor

            pipe = Scale(0.5) | Scale(2.0)   # Sequential([Scale(0.5), Scale(2.0)])
            assert pipe(10.0) == 10.0
    """

    forbid_in_yaml: ClassVar[bool] = False
    _terminal: ClassVar[bool] = False
    backends: ClassVar[tuple[str, ...] | None] = None
    traceable: ClassVar[bool] = True
    # Stateful-pipeline marker — `StatefulOperator` overrides to True; the
    # `Sequential` plumbing reads this to decide whether to thread state.
    # See `pipekit_ops.core` (Group M).
    _is_stateful: ClassVar[bool] = False

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        """Dispatch eager vs symbolic on positional arguments.

        If any positional argument is a `Node` (which `Input` subclasses),
        all positional args must be `Node`s and the call returns a new
        `Node` recording this operator and its parents. Otherwise the
        call routes to `_apply`. Subclasses override `_apply`, not
        `__call__`.

        Raises:
            BackendError: ``backends`` is set, and the inputs sit on a
                backend that cannot move to one it lists, or are traced and
                it does not list JAX.
            TypeError: if graph-construction mode is triggered (at
                least one `Node` arg) but other positional args are not
                `Node`s. Mixing nodes and literals would crash
                downstream when `Graph` walks ``parents``; reject it at
                construction with a clear message.
        """
        # Lazy import to break the operator <-> graph circular dependency.
        from pipekit_ops.core._graph import Node

        if any(isinstance(a, Node) for a in args):
            non_node = [
                (i, type(a).__name__)
                for i, a in enumerate(args)
                if not isinstance(a, Node)
            ]
            if non_node:
                raise TypeError(
                    f"{type(self).__name__}: graph-construction mode requires "
                    "every positional arg to be a Node. Non-Node arg(s) at "
                    f"position(s) {non_node!r}. Wrap literals in `Const(value)` "
                    "or supply them as a separate `Input`."
                )
            return Node(operator=self, parents=tuple(args))
        placed, named, on_host = self._place_inputs(args, kwargs)
        out = self._apply(*placed, **named)
        if on_host:
            out = to_backend(out, "jax")
        # Reserved hook dispatch — no-op in v0.1; Spy/Hook family lands later
        # without requiring every Operator subclass to be edited.
        self._dispatch_post_apply_hooks(args, out)
        return out

    def _place_inputs(
        self,
        args: tuple[Any, ...],
        kwargs: dict[str, Any],
        backends: tuple[str, ...] | None = None,
    ) -> tuple[tuple[Any, ...], dict[str, Any], bool]:
        """The inputs on a backend of ``backends``, and whether JAX data left JAX.

        ``backends`` is the class's own unless an override passes another (a
        `pipekit_array.KernelOp` has its kernel's).

        `__call__` runs it before ``_apply``, and returns the result to JAX
        when the third value is True; anything else that calls ``_apply``
        directly (`AsyncMap` awaiting a coroutine ``_apply``) does both too.

        Raises:
            BackendError: The inputs break ``backends``.
        """
        runs_on = self.backends if backends is None else backends
        if runs_on is None:
            return args, kwargs, False
        return _place(type(self).__name__, runs_on, args, kwargs)

    def _apply(self, *args: Any, **kwargs: Any) -> Any:
        """Implement the operator's behaviour. Override in subclasses."""
        raise NotImplementedError(f"{type(self).__name__} must implement _apply().")

    def _dispatch_post_apply_hooks(self, args: tuple[Any, ...], out: Any) -> None:
        """No-op in v0.1. Reserved for the Spy/Hook family (Group E v0.2)."""
        return None

    def compute_output_signature(self, input_signature: Any) -> Any:
        """Return the signature of this operator's output given an input signature.

        Default is passthrough — most carrier-agnostic operators preserve
        shape and dtype. Subclasses that reshape / reduce / retype override.
        Returning ``None`` signals "this operator does not track shape"
        (carriers without named dimensions); `Sequential.summary` and
        `Graph.summary` show ``?`` for it, and every later step in a
        `Sequential` is unknown too.

        Handed a carrier instead of a signature, the default reads the
        carrier's `Signature` through its registered adapter
        (`pipekit_ops.carriers.signature_of`), so ``Sequential.summary`` can
        start from data.

        The annotation is `Any` rather than `Signature | None` so domain
        libraries can thread their own signature types.
        """
        return signature_of(input_signature)

    @property
    def state(self) -> dict[str, Any]:
        """Return a JSON-serialisable state record for this operator."""
        return {
            "module": type(self).__module__,
            "class": type(self).__name__,
            "config": self.get_config(),
        }

    @classmethod
    def from_state(cls, state: dict[str, Any]) -> Operator:
        """Reconstruct an operator, and any operators nested in it, from `state`.

        Resolves classes among `cls` and all its transitive subclasses,
        so ``Operator.from_state(state)`` resolves any imported subclass;
        nothing is imported. Config values are rebuilt recursively: a
        nested `state` record becomes an operator, an
        ``{"exception": "module.Name"}`` record becomes that (already
        imported) exception class, lists and dicts are rebuilt item by
        item, and JSON primitives pass through. The class's
        `from_config` then builds the operator.

        Raises:
            ValueError: if a state record is malformed.
            TypeError: if a class isn't a loaded `Operator` subclass, or an
                exception record doesn't name a loaded exception class.
            RuntimeError: if any class in the tree is marked
                ``forbid_in_yaml``, or a config holds a value that is not
                JSON (or a nested payload without a ``module``, as
                written before nested round-trips existed).
        """
        module_name, class_name, _ = _check_record(state)
        op_type = resolve_loaded(module_name, class_name)
        if not issubclass(op_type, cls):
            raise TypeError(f"{module_name}.{class_name} is not a {cls.__name__}.")
        return build_operator(state, resolve_loaded)

    @classmethod
    def from_config(cls, config: dict[str, Any]) -> Self:
        """Build an operator from its decoded `get_config()` record.

        The default calls ``cls(**config)``, which is right for every
        operator whose config keys are its constructor's arguments.
        Operators whose config is not a constructor call (`Graph`,
        whose config is a topology) override this.

        Args:
            config: The config with nested operators already rebuilt.
        """
        return cls(**config)

    def __repr__(self) -> str:
        params = ", ".join(f"{k}={v!r}" for k, v in self.get_config().items())
        return f"{type(self).__name__}({params})"

    def __or__(self, other: Operator) -> Sequential:
        """``op1 | op2`` returns ``Sequential([op1, op2])``, flattening on the right.

        ``a | (b | c)`` produces a single three-element `Sequential`.
        """
        # Lazy import — Sequential subclasses Operator.
        from pipekit_ops.core._sequential import Sequential

        if not isinstance(other, Operator):
            return NotImplemented
        if isinstance(other, Sequential):
            return Sequential([self, *other.operators])
        return Sequential([self, other])

state: dict[str, Any] property

Return a JSON-serialisable state record for this operator.

__call__(*args: Any, **kwargs: Any) -> Any

Dispatch eager vs symbolic on positional arguments.

If any positional argument is a Node (which Input subclasses), all positional args must be Nodes and the call returns a new Node recording this operator and its parents. Otherwise the call routes to _apply. Subclasses override _apply, not __call__.

Raises:

Type Description
BackendError

backends is set, and the inputs sit on a backend that cannot move to one it lists, or are traced and it does not list JAX.

TypeError

if graph-construction mode is triggered (at least one Node arg) but other positional args are not Nodes. Mixing nodes and literals would crash downstream when Graph walks parents; reject it at construction with a clear message.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
def __call__(self, *args: Any, **kwargs: Any) -> Any:
    """Dispatch eager vs symbolic on positional arguments.

    If any positional argument is a `Node` (which `Input` subclasses),
    all positional args must be `Node`s and the call returns a new
    `Node` recording this operator and its parents. Otherwise the
    call routes to `_apply`. Subclasses override `_apply`, not
    `__call__`.

    Raises:
        BackendError: ``backends`` is set, and the inputs sit on a
            backend that cannot move to one it lists, or are traced and
            it does not list JAX.
        TypeError: if graph-construction mode is triggered (at
            least one `Node` arg) but other positional args are not
            `Node`s. Mixing nodes and literals would crash
            downstream when `Graph` walks ``parents``; reject it at
            construction with a clear message.
    """
    # Lazy import to break the operator <-> graph circular dependency.
    from pipekit_ops.core._graph import Node

    if any(isinstance(a, Node) for a in args):
        non_node = [
            (i, type(a).__name__)
            for i, a in enumerate(args)
            if not isinstance(a, Node)
        ]
        if non_node:
            raise TypeError(
                f"{type(self).__name__}: graph-construction mode requires "
                "every positional arg to be a Node. Non-Node arg(s) at "
                f"position(s) {non_node!r}. Wrap literals in `Const(value)` "
                "or supply them as a separate `Input`."
            )
        return Node(operator=self, parents=tuple(args))
    placed, named, on_host = self._place_inputs(args, kwargs)
    out = self._apply(*placed, **named)
    if on_host:
        out = to_backend(out, "jax")
    # Reserved hook dispatch — no-op in v0.1; Spy/Hook family lands later
    # without requiring every Operator subclass to be edited.
    self._dispatch_post_apply_hooks(args, out)
    return out

__or__(other: Operator) -> Sequential

op1 | op2 returns Sequential([op1, op2]), flattening on the right.

a | (b | c) produces a single three-element Sequential.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
def __or__(self, other: Operator) -> Sequential:
    """``op1 | op2`` returns ``Sequential([op1, op2])``, flattening on the right.

    ``a | (b | c)`` produces a single three-element `Sequential`.
    """
    # Lazy import — Sequential subclasses Operator.
    from pipekit_ops.core._sequential import Sequential

    if not isinstance(other, Operator):
        return NotImplemented
    if isinstance(other, Sequential):
        return Sequential([self, *other.operators])
    return Sequential([self, other])

compute_output_signature(input_signature: Any) -> Any

Return the signature of this operator's output given an input signature.

Default is passthrough — most carrier-agnostic operators preserve shape and dtype. Subclasses that reshape / reduce / retype override. Returning None signals "this operator does not track shape" (carriers without named dimensions); Sequential.summary and Graph.summary show ? for it, and every later step in a Sequential is unknown too.

Handed a carrier instead of a signature, the default reads the carrier's Signature through its registered adapter (pipekit_ops.carriers.signature_of), so Sequential.summary can start from data.

The annotation is Any rather than Signature | None so domain libraries can thread their own signature types.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
def compute_output_signature(self, input_signature: Any) -> Any:
    """Return the signature of this operator's output given an input signature.

    Default is passthrough — most carrier-agnostic operators preserve
    shape and dtype. Subclasses that reshape / reduce / retype override.
    Returning ``None`` signals "this operator does not track shape"
    (carriers without named dimensions); `Sequential.summary` and
    `Graph.summary` show ``?`` for it, and every later step in a
    `Sequential` is unknown too.

    Handed a carrier instead of a signature, the default reads the
    carrier's `Signature` through its registered adapter
    (`pipekit_ops.carriers.signature_of`), so ``Sequential.summary`` can
    start from data.

    The annotation is `Any` rather than `Signature | None` so domain
    libraries can thread their own signature types.
    """
    return signature_of(input_signature)

from_config(config: dict[str, Any]) -> Self classmethod

Build an operator from its decoded get_config() record.

The default calls cls(**config), which is right for every operator whose config keys are its constructor's arguments. Operators whose config is not a constructor call (Graph, whose config is a topology) override this.

Parameters:

Name Type Description Default
config dict[str, Any]

The config with nested operators already rebuilt.

required
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
@classmethod
def from_config(cls, config: dict[str, Any]) -> Self:
    """Build an operator from its decoded `get_config()` record.

    The default calls ``cls(**config)``, which is right for every
    operator whose config keys are its constructor's arguments.
    Operators whose config is not a constructor call (`Graph`,
    whose config is a topology) override this.

    Args:
        config: The config with nested operators already rebuilt.
    """
    return cls(**config)

from_state(state: dict[str, Any]) -> Operator classmethod

Reconstruct an operator, and any operators nested in it, from state.

Resolves classes among cls and all its transitive subclasses, so Operator.from_state(state) resolves any imported subclass; nothing is imported. Config values are rebuilt recursively: a nested state record becomes an operator, an {"exception": "module.Name"} record becomes that (already imported) exception class, lists and dicts are rebuilt item by item, and JSON primitives pass through. The class's from_config then builds the operator.

Raises:

Type Description
ValueError

if a state record is malformed.

TypeError

if a class isn't a loaded Operator subclass, or an exception record doesn't name a loaded exception class.

RuntimeError

if any class in the tree is marked forbid_in_yaml, or a config holds a value that is not JSON (or a nested payload without a module, as written before nested round-trips existed).

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
@classmethod
def from_state(cls, state: dict[str, Any]) -> Operator:
    """Reconstruct an operator, and any operators nested in it, from `state`.

    Resolves classes among `cls` and all its transitive subclasses,
    so ``Operator.from_state(state)`` resolves any imported subclass;
    nothing is imported. Config values are rebuilt recursively: a
    nested `state` record becomes an operator, an
    ``{"exception": "module.Name"}`` record becomes that (already
    imported) exception class, lists and dicts are rebuilt item by
    item, and JSON primitives pass through. The class's
    `from_config` then builds the operator.

    Raises:
        ValueError: if a state record is malformed.
        TypeError: if a class isn't a loaded `Operator` subclass, or an
            exception record doesn't name a loaded exception class.
        RuntimeError: if any class in the tree is marked
            ``forbid_in_yaml``, or a config holds a value that is not
            JSON (or a nested payload without a ``module``, as
            written before nested round-trips existed).
    """
    module_name, class_name, _ = _check_record(state)
    op_type = resolve_loaded(module_name, class_name)
    if not issubclass(op_type, cls):
        raise TypeError(f"{module_name}.{class_name} is not a {cls.__name__}.")
    return build_operator(state, resolve_loaded)

pipekit_ops.ConfigMixin

Auto-derive get_config() from __init__ parameter names.

Reads inspect.signature(type(self).__init__), then for each declared parameter name looks up the matching instance attribute on self. The discipline: store __init__ kwargs as attributes of the same name (the geotoolz / xr_toolz convention).

Opt-out: set __config_mixin_auto__ = False to disable auto-derivation entirely (subclasses then must override get_config themselves).

Exclude: set __config_exclude__ = ("field_a",) to skip specific parameters (useful for runtime-only state).

Subclasses can override get_config directly when auto-derivation isn't appropriate (e.g. Sequential whose config is a list of nested operators, not constructor parameters).

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
class ConfigMixin:
    """Auto-derive `get_config()` from `__init__` parameter names.

    Reads `inspect.signature(type(self).__init__)`, then for each
    declared parameter name looks up the matching instance attribute on
    `self`. The discipline: store `__init__` kwargs as attributes of the
    same name (the geotoolz / xr_toolz convention).

    Opt-out: set ``__config_mixin_auto__ = False`` to disable
    auto-derivation entirely (subclasses then must override
    `get_config` themselves).

    Exclude: set ``__config_exclude__ = ("field_a",)`` to skip specific
    parameters (useful for runtime-only state).

    Subclasses can override `get_config` directly when auto-derivation
    isn't appropriate (e.g. `Sequential` whose config is a list of
    nested operators, not constructor parameters).
    """

    __config_mixin_auto__: ClassVar[bool] = True
    __config_exclude__: ClassVar[tuple[str, ...]] = ()

    def get_config(self) -> dict[str, Any]:
        """Return a JSON-serialisable dict of constructor args."""
        if not type(self).__config_mixin_auto__:
            return {}
        try:
            sig = inspect.signature(type(self).__init__)
        except (TypeError, ValueError):
            return {}
        excluded = set(type(self).__config_exclude__)
        config: dict[str, Any] = {}
        for name, param in sig.parameters.items():
            if name == "self":
                continue
            if param.kind in (
                inspect.Parameter.VAR_POSITIONAL,
                inspect.Parameter.VAR_KEYWORD,
            ):
                continue
            if name in excluded:
                continue
            if hasattr(self, name):
                config[name] = getattr(self, name)
        return config

get_config()

Return a JSON-serialisable dict of constructor args.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_operator.py
def get_config(self) -> dict[str, Any]:
    """Return a JSON-serialisable dict of constructor args."""
    if not type(self).__config_mixin_auto__:
        return {}
    try:
        sig = inspect.signature(type(self).__init__)
    except (TypeError, ValueError):
        return {}
    excluded = set(type(self).__config_exclude__)
    config: dict[str, Any] = {}
    for name, param in sig.parameters.items():
        if name == "self":
            continue
        if param.kind in (
            inspect.Parameter.VAR_POSITIONAL,
            inspect.Parameter.VAR_KEYWORD,
        ):
            continue
        if name in excluded:
            continue
        if hasattr(self, name):
            config[name] = getattr(self, name)
    return config

Linear composition

pipekit_ops.Sequential

Bases: Operator

Apply a list of operators in order, threading the output of each into the next.

Parameters:

Name Type Description Default
operators list[Operator]

A list of Operator instances. The empty list is allowed but degenerate: Sequential([])(x) returns x unchanged, while Sequential([])() raises TypeError (the empty pipeline has no first operator to consult, and the carrier has to come from somewhere).

required

Raises:

Type Description
TypeError

if any element is not an Operator, or if any non-final element is marked _terminal.

Example

Basic::

pipe = Sequential([Scale(0.5), Scale(2.0)])
assert pipe(10.0) == 10.0

Slice into a sub-pipeline::

head = pipe[:1]   # Sequential([Scale(0.5)])

Index a single step::

first = pipe[0]   # Scale(0.5)
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_sequential.py
class Sequential(Operator):
    """Apply a list of operators in order, threading the output of each into the next.

    Args:
        operators: A list of `Operator` instances. The empty list is
            allowed but degenerate: ``Sequential([])(x)`` returns ``x``
            unchanged, while ``Sequential([])()`` raises `TypeError`
            (the empty pipeline has no first operator to consult, and
            the carrier has to come from somewhere).

    Raises:
        TypeError: if any element is not an `Operator`, or if any
            non-final element is marked ``_terminal``.

    Example:
        Basic::

            pipe = Sequential([Scale(0.5), Scale(2.0)])
            assert pipe(10.0) == 10.0

        Slice into a sub-pipeline::

            head = pipe[:1]   # Sequential([Scale(0.5)])

        Index a single step::

            first = pipe[0]   # Scale(0.5)
    """

    __config_mixin_auto__ = False  # custom get_config — nested-operator list

    def __init__(self, operators: list[Operator]) -> None:
        for i, op in enumerate(operators):
            require_operator(op, "Sequential", f"operators[{i}]")
        for i, op in enumerate(operators[:-1]):
            if op._terminal:
                raise TypeError(
                    f"Sequential[{i}] is a terminal operator "
                    f"({type(op).__name__}) — terminal operators are only "
                    "valid as the last step of a Sequential."
                )
        self.operators = list(operators)

    @property
    def _is_stateful(self) -> bool:  # type: ignore[override]
        """True if any contained operator is a `StatefulOperator`.

        Overrides the ``_is_stateful: ClassVar[bool] = False`` default
        on `Operator` with a per-instance property — the answer depends
        on what the user composed.
        """
        return any(getattr(op, "_is_stateful", False) for op in self.operators)

    @property
    def is_stateful(self) -> bool:
        """True if any contained operator is a `StatefulOperator`.

        Such a pipeline is called as ``pipe(carrier, state)`` and returns
        ``(carrier, state)``, so it can step a pipekit-cycle cycle.
        """
        return self._is_stateful

    def _apply(self, carrier: Carrier = _MISSING, state: Any = _MISSING) -> Any:
        """Run the pipeline, dispatching between stateless and stateful modes.

        Stateless (the common case): thread ``carrier`` through each
        operator left to right. Stateful — chosen when a ``state`` kwarg
        is supplied or any step is a `StatefulOperator` — delegates to
        `_apply_stateful`, which threads ``(carrier, state)`` pairs. The
        `_MISSING` sentinel distinguishes "argument omitted" from an
        explicit ``None`` so ``pipe(None)`` still means "carrier is None".

        Raises:
            TypeError: Calling an empty pipeline with no input, or
                supplying ``state`` without a carrier.
        """
        if carrier is _MISSING and not self.operators:
            raise TypeError(
                "Sequential([]) cannot be called without an input: "
                "empty pipeline has no operations to perform."
            )
        # Stateful path: any stateful op present *or* state explicitly supplied.
        if state is not _MISSING or self._is_stateful:
            if state is _MISSING:
                raise TypeError(
                    "Sequential contains StatefulOperator(s) but was called "
                    "without a `state` argument. Supply the initial CarryState."
                )
            if carrier is _MISSING:
                raise TypeError(
                    "Sequential was called with `state` but no carrier. "
                    "Stateful pipelines need both: pipe(carrier, state)."
                )
            return self._apply_stateful(carrier, state)
        # Stateless path — original behaviour.
        if carrier is _MISSING:
            out = self.operators[0]()
            remaining = self.operators[1:]
        else:
            out = carrier
            remaining = self.operators
        for op in remaining:
            out = op(out)
        return out

    def _apply_stateful(self, carrier: Carrier, state: Any) -> tuple[Any, Any]:
        """Thread state through stateful ops; pass through stateless ones unchanged.

        Returns ``(carrier, state)`` so the caller can checkpoint or
        feed the state back into the next call.
        """
        out = carrier
        for op in self.operators:
            if getattr(op, "_is_stateful", False):
                out, state = op(out, state)
            else:
                out = op(out)
        return out, state

    def compute_output_signature(self, input_signature: Any) -> Any:
        """Thread the signature through every operator in order.

        A registered carrier is read as its `Signature` first.
        """
        sig = signature_of(input_signature)
        for op in self.operators:
            sig = op.compute_output_signature(sig)
            if sig is None:
                return None
        return sig

    def get_config(self) -> dict[str, Any]:
        return {"operators": [nested_config(op) for op in self.operators]}

    def __or__(self, other: Operator) -> Sequential:
        """Append on the right; flatten nested `Sequential`s."""
        if not isinstance(other, Operator):
            return NotImplemented
        if isinstance(other, Sequential):
            return Sequential([*self.operators, *other.operators])
        return Sequential([*self.operators, other])

    def __repr__(self) -> str:
        if not self.operators:
            return "Sequential([])"
        inner = ", ".join(repr(op) for op in self.operators)
        return f"Sequential([{inner}])"

    def __len__(self) -> int:
        return len(self.operators)

    def __getitem__(self, key: int | slice) -> Operator | Sequential:
        """Index or slice into the underlying operator list.

        ``pipe[0]`` returns the first operator. ``pipe[1:3]`` returns a
        new `Sequential` containing the slice.
        """
        if isinstance(key, slice):
            return Sequential(self.operators[key])
        return self.operators[key]

    def describe(self, indent: int = 0) -> str:
        """Return an indented-tree pretty-print of the pipeline.

        Recurses into nested `Sequential` / `Graph` operators. Useful
        for notebook exploration; not parsed.
        """
        pad = "  " * indent
        if not self.operators:
            return f"{pad}Sequential([])"
        lines: list[str] = [f"{pad}Sequential(["]
        for op in self.operators:
            if isinstance(op, Sequential):
                lines.append(op.describe(indent=indent + 1) + ",")
            else:
                lines.append(f"{pad}  {op!r},")
        lines.append(f"{pad}])")
        return "\n".join(lines)

    def summary(self, input_signature: Any = None) -> str:
        """Render a Keras-style summary table.

        Threads ``input_signature`` through `compute_output_signature`;
        a registered carrier is read as its `Signature` first. If any
        operator returns ``None`` (does not track shape), the summary
        still lists the operator but shows ``?`` for its output
        signature. With ``input_signature=None``, only operator names
        and types are shown.

        The return type is ``str`` rather than printing directly so the
        caller decides where it goes (notebook, log, file).
        """
        rows: list[tuple[str, str, str]] = []
        sig = signature_of(input_signature)
        for i, op in enumerate(self.operators):
            sig_in = "?" if sig is None else repr(sig)
            sig = op.compute_output_signature(sig)
            sig_out = "?" if sig is None else repr(sig)
            rows.append((f"[{i}] {type(op).__name__}", sig_in, sig_out))

        # Column widths
        w_name = max((len(r[0]) for r in rows), default=4)
        w_in = max((len(r[1]) for r in rows), default=8)
        w_out = max((len(r[2]) for r in rows), default=8)

        header = (
            f"{'Operator'.ljust(w_name)}  "
            f"{'Input sig'.ljust(w_in)}  "
            f"{'Output sig'.ljust(w_out)}"
        )
        rule = "-" * len(header)
        body = [
            f"{name.ljust(w_name)}  {sin.ljust(w_in)}  {sout.ljust(w_out)}"
            for name, sin, sout in rows
        ]
        return "\n".join([header, rule, *body])

is_stateful: bool property

True if any contained operator is a StatefulOperator.

Such a pipeline is called as pipe(carrier, state) and returns (carrier, state), so it can step a pipekit-cycle cycle.

__getitem__(key: int | slice) -> Operator | Sequential

Index or slice into the underlying operator list.

pipe[0] returns the first operator. pipe[1:3] returns a new Sequential containing the slice.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_sequential.py
def __getitem__(self, key: int | slice) -> Operator | Sequential:
    """Index or slice into the underlying operator list.

    ``pipe[0]`` returns the first operator. ``pipe[1:3]`` returns a
    new `Sequential` containing the slice.
    """
    if isinstance(key, slice):
        return Sequential(self.operators[key])
    return self.operators[key]

__or__(other: Operator) -> Sequential

Append on the right; flatten nested Sequentials.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_sequential.py
def __or__(self, other: Operator) -> Sequential:
    """Append on the right; flatten nested `Sequential`s."""
    if not isinstance(other, Operator):
        return NotImplemented
    if isinstance(other, Sequential):
        return Sequential([*self.operators, *other.operators])
    return Sequential([*self.operators, other])

compute_output_signature(input_signature: Any) -> Any

Thread the signature through every operator in order.

A registered carrier is read as its Signature first.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_sequential.py
def compute_output_signature(self, input_signature: Any) -> Any:
    """Thread the signature through every operator in order.

    A registered carrier is read as its `Signature` first.
    """
    sig = signature_of(input_signature)
    for op in self.operators:
        sig = op.compute_output_signature(sig)
        if sig is None:
            return None
    return sig

describe(indent: int = 0) -> str

Return an indented-tree pretty-print of the pipeline.

Recurses into nested Sequential / Graph operators. Useful for notebook exploration; not parsed.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_sequential.py
def describe(self, indent: int = 0) -> str:
    """Return an indented-tree pretty-print of the pipeline.

    Recurses into nested `Sequential` / `Graph` operators. Useful
    for notebook exploration; not parsed.
    """
    pad = "  " * indent
    if not self.operators:
        return f"{pad}Sequential([])"
    lines: list[str] = [f"{pad}Sequential(["]
    for op in self.operators:
        if isinstance(op, Sequential):
            lines.append(op.describe(indent=indent + 1) + ",")
        else:
            lines.append(f"{pad}  {op!r},")
    lines.append(f"{pad}])")
    return "\n".join(lines)

summary(input_signature: Any = None) -> str

Render a Keras-style summary table.

Threads input_signature through compute_output_signature; a registered carrier is read as its Signature first. If any operator returns None (does not track shape), the summary still lists the operator but shows ? for its output signature. With input_signature=None, only operator names and types are shown.

The return type is str rather than printing directly so the caller decides where it goes (notebook, log, file).

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_sequential.py
def summary(self, input_signature: Any = None) -> str:
    """Render a Keras-style summary table.

    Threads ``input_signature`` through `compute_output_signature`;
    a registered carrier is read as its `Signature` first. If any
    operator returns ``None`` (does not track shape), the summary
    still lists the operator but shows ``?`` for its output
    signature. With ``input_signature=None``, only operator names
    and types are shown.

    The return type is ``str`` rather than printing directly so the
    caller decides where it goes (notebook, log, file).
    """
    rows: list[tuple[str, str, str]] = []
    sig = signature_of(input_signature)
    for i, op in enumerate(self.operators):
        sig_in = "?" if sig is None else repr(sig)
        sig = op.compute_output_signature(sig)
        sig_out = "?" if sig is None else repr(sig)
        rows.append((f"[{i}] {type(op).__name__}", sig_in, sig_out))

    # Column widths
    w_name = max((len(r[0]) for r in rows), default=4)
    w_in = max((len(r[1]) for r in rows), default=8)
    w_out = max((len(r[2]) for r in rows), default=8)

    header = (
        f"{'Operator'.ljust(w_name)}  "
        f"{'Input sig'.ljust(w_in)}  "
        f"{'Output sig'.ljust(w_out)}"
    )
    rule = "-" * len(header)
    body = [
        f"{name.ljust(w_name)}  {sin.ljust(w_in)}  {sout.ljust(w_out)}"
        for name, sin, sout in rows
    ]
    return "\n".join([header, rule, *body])

Graphs

pipekit_ops.Input

Bases: Node

A named entry point into a Graph.

Operator.__call__ recognises Node (and any subclass, including Input) as graph-construction mode. Graph._apply supplies the value at run-time from the caller's kwargs / positional args.

Subclassing Node (master plan Report 2.A.3, "xr_toolz shape") lets the topological sort treat all vertices uniformly with one special case: "this node has no operator — source it from the caller's inputs".

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
class Input(Node):
    """A named entry point into a `Graph`.

    `Operator.__call__` recognises `Node` (and any subclass, including
    `Input`) as graph-construction mode. `Graph._apply` supplies the
    value at run-time from the caller's kwargs / positional args.

    Subclassing `Node` (master plan Report 2.A.3, "xr_toolz shape")
    lets the topological sort treat all vertices uniformly with one
    special case: "this node has no operator — source it from the
    caller's inputs".
    """

    __slots__ = ("name",)

    def __init__(self, name: str) -> None:
        super().__init__(operator=None, parents=())
        self.name = name

pipekit_ops.Node

A vertex in a Graph.

Created automatically by Operator.__call__ when any positional argument is a Node (or Input, which subclasses Node). Carries the operator and its parent vertices. Compared by identity so the id(...)-keyed evaluation cache during topological sort works.

Raises:

Type Description
TypeError

if any element of parents is not a Node. Graph evaluation walks parents recursively and indexes an id(...)-keyed cache; non-Node parents would crash with an unhelpful KeyError deep in the traversal.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
class Node:
    """A vertex in a `Graph`.

    Created automatically by `Operator.__call__` when any positional
    argument is a `Node` (or `Input`, which subclasses `Node`). Carries
    the operator and its parent vertices. Compared by identity so the
    ``id(...)``-keyed evaluation cache during topological sort works.

    Raises:
        TypeError: if any element of ``parents`` is not a `Node`.
            `Graph` evaluation walks ``parents`` recursively and indexes
            an ``id(...)``-keyed cache; non-Node parents would crash with
            an unhelpful ``KeyError`` deep in the traversal.
    """

    __slots__ = ("operator", "parents")

    def __init__(
        self,
        operator: Operator | None,
        parents: tuple[Any, ...],
    ) -> None:
        for i, p in enumerate(parents):
            if not isinstance(p, Node):
                raise TypeError(
                    f"Node.parents[{i}] is {type(p).__name__}, expected Node. "
                    "Wrap literal values in `Const(value)` to lift them into "
                    "the graph."
                )
        self.operator = operator
        self.parents = parents

    def __eq__(self, other: object) -> bool:
        return self is other

    def __hash__(self) -> int:
        return id(self)

pipekit_ops.Graph

Bases: Operator

A symbolic operator graph with multiple inputs and outputs.

Construction is implicit — calling operators on Input / Node instances builds the graph; Graph(inputs=..., outputs=...) wraps the result. _apply(**inputs) evaluates in topological order.

Inherits from Operator so a Graph satisfies the same interface as any other operator. Operator.__call__ dispatches keyword args straight through to Graph._apply; positional args are bound to declared Inputs in declaration order.

Parameters:

Name Type Description Default
inputs dict[str, Input]

Map of input-name → Input placeholders. The keys are the keyword names accepted by __call__.

required
outputs dict[str, Node]

Map of output-name → Node (or Input, if the output is a direct passthrough). The keys are the keys of the returned dict.

required
State

A graph that contains a stateful node (a StatefulOperator, or a Sequential / Graph that contains one) threads a carry state the way Sequential does: call it as graph(a=..., b=..., state=s) and it returns (outputs, state). The state passes through the stateful nodes in topological order (the order describe lists); stateless nodes ignore it. Inside a stateful Sequential the graph receives (carrier, state) positionally, like any stateful step.

Raises:

Type Description
ValueError

if the graph contains a cycle, if an Input referenced by a node isn't declared in inputs, if a required input is missing at call time, or if a stateful graph declares an input named state (the name is the carry state's).

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
class Graph(Operator):
    """A symbolic operator graph with multiple inputs and outputs.

    Construction is implicit — calling operators on `Input` / `Node`
    instances builds the graph; ``Graph(inputs=..., outputs=...)``
    wraps the result. ``_apply(**inputs)`` evaluates in topological
    order.

    Inherits from `Operator` so a `Graph` satisfies the same interface
    as any other operator. ``Operator.__call__`` dispatches keyword
    args straight through to `Graph._apply`; positional args are bound
    to declared `Input`s in declaration order.

    Args:
        inputs: Map of ``input-name → Input`` placeholders. The keys
            are the keyword names accepted by ``__call__``.
        outputs: Map of ``output-name → Node`` (or ``Input``, if the
            output is a direct passthrough). The keys are the keys of
            the returned dict.

    State:
        A graph that contains a stateful node (a `StatefulOperator`, or
        a `Sequential` / `Graph` that contains one) threads a carry state
        the way `Sequential` does: call it as
        ``graph(a=..., b=..., state=s)`` and it returns
        ``(outputs, state)``. The state passes through the stateful nodes
        in topological order (the order `describe` lists); stateless
        nodes ignore it. Inside a stateful `Sequential` the graph receives
        ``(carrier, state)`` positionally, like any stateful step.

    Raises:
        ValueError: if the graph contains a cycle, if an `Input`
            referenced by a node isn't declared in ``inputs``, if a
            required input is missing at call time, or if a stateful
            graph declares an input named ``state`` (the name is the
            carry state's).
    """

    __config_mixin_auto__ = False  # custom get_config — topology, not kwargs

    def __init__(
        self,
        inputs: dict[str, Input],
        outputs: dict[str, Node],
    ) -> None:
        self.inputs = inputs
        self.outputs = outputs
        self._order = self._topological_sort()
        if self._is_stateful and "state" in inputs:
            raise ValueError(
                "A stateful Graph cannot declare an input named 'state': "
                "`state=` is how its carry state is passed. Rename the input."
            )

    @property
    def _is_stateful(self) -> bool:  # type: ignore[override]
        """True if any node's operator is stateful (as for `Sequential`)."""
        return any(
            getattr(node.operator, "_is_stateful", False) for node in self._order
        )

    def _topological_sort(self) -> list[Node]:
        """Return the topological ordering of non-input `Node`s.

        Inputs are sources (supplied by the caller) and are not
        included in the work list. Direct-passthrough outputs (an
        `Input` listed under ``outputs=``) are likewise skipped.
        """
        declared_inputs = set(map(id, self.inputs.values()))
        order: list[Node] = []
        visited: set[int] = set()
        on_stack: set[int] = set()

        def visit(node: Node) -> None:
            node_id = id(node)
            if node_id in visited:
                return
            if node_id in on_stack:
                raise ValueError(
                    "Cycle detected in graph — operator graphs must be DAGs."
                )
            on_stack.add(node_id)
            for parent in node.parents:
                visit(parent)
            on_stack.discard(node_id)
            visited.add(node_id)
            if isinstance(node, Input):
                if node_id not in declared_inputs:
                    raise ValueError(
                        f"Input {node.name!r} is referenced by an output but "
                        "not declared in `inputs=`."
                    )
                return
            order.append(node)

        for output in self.outputs.values():
            visit(output)
        return order

    def _apply(self, *args: Carrier, **inputs: Carrier) -> Any:
        """Evaluate the graph with the supplied inputs (and carry state).

        Accepts inputs either positionally (bound to declared `Input`s
        in declaration order) or by keyword. The positional form lets
        single-input graphs compose into `Sequential` cleanly and lets
        graphs nest inside other graphs — both shapes route values
        through `Operator.__call__`, which only splat positionally.

        Args:
            *args: One value per declared `Input`, in declaration order,
                then, for a stateful call, the state. Mutually exclusive
                with ``**inputs``.
            **inputs: One value per declared `Input`, keyed by name, and
                ``state=`` for a stateful call (unless ``state`` is a
                declared input of a stateless graph).

        Returns:
            ``{output-name: result}`` for each declared output; for a
            stateful call, ``(outputs, state)``.

        Raises:
            TypeError: if positional and keyword inputs are mixed, if the
                number of positional arguments fits neither the inputs
                nor the inputs plus a state, or if a stateful graph is
                called without a state.
        """
        if args and inputs:
            raise TypeError(
                "Graph._apply accepts either positional args (bound to inputs "
                "in declaration order) or keyword inputs, not both."
            )
        state: Any = _MISSING
        if args and len(args) == len(self.inputs) + 1:
            # (carrier..., state): how a stateful Sequential or Graph calls it
            *args_list, state = args
            args = tuple(args_list)
        if "state" in inputs and "state" not in self.inputs:
            state = inputs.pop("state")
        if self._is_stateful and state is _MISSING:
            raise TypeError(
                "Graph contains stateful operator(s) but was called without a "
                "`state` argument. Supply the initial CarryState: "
                "graph(..., state=s)."
            )
        if args:
            if len(args) != len(self.inputs):
                raise TypeError(
                    f"Graph expected {len(self.inputs)} positional argument(s) "
                    f"to bind to inputs {list(self.inputs)}, got {len(args)}."
                )
            inputs = dict(zip(self.inputs, args, strict=True))

        missing = set(self.inputs) - set(inputs)
        if missing:
            raise ValueError(f"Graph missing required input(s): {sorted(missing)}")

        cache: dict[int, Any] = {
            id(self.inputs[name]): inputs[name] for name in self.inputs
        }
        for node in self._order:
            assert node.operator is not None  # guaranteed by _topological_sort
            node_args = tuple(cache[id(p)] for p in node.parents)
            # Route through __call__ so nested operators (Graph, Sequential)
            # get their own dispatch, not just bare _apply.
            if state is not _MISSING and getattr(node.operator, "_is_stateful", False):
                # stateful nodes take the state last and hand it on, in order
                cache[id(node)], state = node.operator(*node_args, state)
            else:
                cache[id(node)] = node.operator(*node_args)

        outputs = {name: cache[id(node)] for name, node in self.outputs.items()}
        if state is _MISSING:
            return outputs
        return outputs, state

    def get_config(self) -> dict[str, Any]:
        """The whole topology: inputs, operators, nodes and outputs.

        Every node is recorded, upstream ones included, so two graphs
        that differ anywhere have different configs (and so different
        `state` records and content hashes). The record::

            {
                "inputs": ["image", "reference"],
                "operators": [<state>, ...],
                "nodes": [{"operator": 0, "parents": [{"input": "image"}]}, ...],
                "outputs": {"ndvi": {"node": 0}, "raw": {"input": "image"}},
            }

        ``operators`` lists each distinct operator once, by identity, in
        first-use order, so an operator shared by several nodes is not
        duplicated. ``nodes`` is in topological order; a parent or an
        output refers either to a declared input by name or to an
        earlier node by index.
        """
        input_names = {id(node): name for name, node in self.inputs.items()}
        node_index = {id(node): i for i, node in enumerate(self._order)}
        operator_index: dict[int, int] = {}
        operators: list[dict[str, Any]] = []
        nodes: list[dict[str, Any]] = []

        def ref(node: Node) -> dict[str, Any]:
            if id(node) in input_names:
                return {"input": input_names[id(node)]}
            return {"node": node_index[id(node)]}

        for node in self._order:
            assert node.operator is not None  # guaranteed by _topological_sort
            op_id = id(node.operator)
            if op_id not in operator_index:
                operator_index[op_id] = len(operators)
                operators.append(node.operator.state)
            parents = [ref(parent) for parent in node.parents]
            nodes.append({"operator": operator_index[op_id], "parents": parents})

        return {
            "inputs": list(self.inputs),
            "operators": operators,
            "nodes": nodes,
            "outputs": {name: ref(node) for name, node in self.outputs.items()},
        }

    @classmethod
    def from_config(cls, config: dict[str, Any]) -> Self:
        """Rebuild a graph from the topology `get_config` records.

        Re-creates each `Input`, then calls each node's operator on its
        parents in the recorded order, which wires the nodes exactly as
        they were; an operator shared by several nodes stays one object.

        Args:
            config: A `get_config` record whose ``operators`` have already
                been rebuilt into `Operator` instances.

        Raises:
            ValueError: if a reference names an undeclared input or a node
                that comes later in the order.
        """
        inputs = {name: Input(name) for name in config["inputs"]}
        operators: list[Operator] = config["operators"]
        built: list[Node] = []

        def lookup(ref: dict[str, Any]) -> Node:
            if "input" in ref:
                if ref["input"] not in inputs:
                    raise ValueError(f"Graph config: undeclared input {ref!r}.")
                return inputs[ref["input"]]
            index = ref["node"]
            if not 0 <= index < len(built):
                raise ValueError(f"Graph config: {ref!r} is not an earlier node.")
            return built[index]

        for spec in config["nodes"]:
            parents = [lookup(ref) for ref in spec["parents"]]
            built.append(operators[spec["operator"]](*parents))
        outputs = {name: lookup(ref) for name, ref in config["outputs"].items()}
        return cls(inputs=inputs, outputs=outputs)

    def __repr__(self) -> str:
        ins = ", ".join(self.inputs)
        outs = ", ".join(self.outputs)
        return f"Graph(inputs=[{ins}], outputs=[{outs}])"

    def compute_output_signature(self, input_signature: Any) -> Any:
        """``None``: a graph returns a dict of outputs, not one carrier.

        Use `output_signatures` for each output's signature, and
        `summary` for the whole table.
        """
        return None

    def output_signatures(self, input_signatures: Any) -> dict[str, Any]:
        """Each output's signature, propagated node by node without data.

        Args:
            input_signatures: ``{input name: Signature}``; a missing name
                means unknown. A single-input graph also takes the bare
                signature.

        Returns:
            ``{output name: Signature | None}``; ``None`` where an
            operator does not track shape, or where a multi-input node's
            inputs disagree (see `summary`).
        """
        signatures = self._node_signatures(input_signatures)
        return {name: signatures[id(node)] for name, node in self.outputs.items()}

    def summary(self, input_signatures: Any = None) -> str:
        """A Keras-style table of the nodes, their input and output signatures.

        Nodes are listed in topological order. Signatures propagate
        through each node's `compute_output_signature`; a node with
        several inputs gets its operator's signature for them only when
        they all agree (an elementwise join), and ``?`` otherwise, since
        `compute_output_signature` takes one input. The outputs follow.

        Args:
            input_signatures: As for `output_signatures`; ``None`` lists
                the structure with every signature unknown.
        """
        signatures = self._node_signatures(input_signatures)
        names = {id(node): name for name, node in self.inputs.items()}

        def label(node: Node) -> str:
            if id(node) in names:
                return names[id(node)]
            return f"[{self._order.index(node)}]"

        def show(signature: Any) -> str:
            if signature is None:
                return "?"
            # a Signature's compact "(y=64, x=64) float32" form
            fmt = getattr(signature, "format", None)
            return fmt() if callable(fmt) else repr(signature)

        rows: list[tuple[str, str, str]] = []
        for i, node in enumerate(self._order):
            parents = ", ".join(label(parent) for parent in node.parents)
            sig_in = ", ".join(show(signatures[id(p)]) for p in node.parents) or "-"
            name = f"[{i}] {type(node.operator).__name__}({parents})"
            rows.append((name, sig_in, show(signatures[id(node)])))
        for out_name, node in self.outputs.items():
            rows.append(
                (f"→ {out_name} = {label(node)}", "", show(signatures[id(node)]))
            )

        w_name = max([len("Node"), *(len(r[0]) for r in rows)])
        w_in = max([len("Input sig"), *(len(r[1]) for r in rows)])
        header = f"{'Node'.ljust(w_name)}  {'Input sig'.ljust(w_in)}  Output sig"
        body = [f"{n.ljust(w_name)}  {i.ljust(w_in)}  {o}" for n, i, o in rows]
        return "\n".join([header, "-" * len(header), *body])

    def _node_signatures(self, input_signatures: Any) -> dict[int, Any]:
        """``id(node) → Signature | None`` for every input and node."""
        if input_signatures is None:
            input_signatures = {}
        elif not isinstance(input_signatures, dict):
            if len(self.inputs) != 1:
                raise TypeError(
                    "This graph has several inputs: pass "
                    "{input name: Signature}, not a single signature."
                )
            input_signatures = {next(iter(self.inputs)): input_signatures}
        unknown = sorted(set(input_signatures) - set(self.inputs))
        if unknown:
            raise ValueError(f"Signatures given for undeclared input(s) {unknown}.")

        signatures: dict[int, Any] = {}
        for name, node in self.inputs.items():
            signatures[id(node)] = signature_of(input_signatures.get(name))
        for node in self._order:
            assert node.operator is not None  # guaranteed by _topological_sort
            parents = [signatures[id(parent)] for parent in node.parents]
            if not parents:
                joined = None
            elif all(parent == parents[0] for parent in parents):
                joined = parents[0]
            else:
                # inputs disagree: compute_output_signature takes one input
                signatures[id(node)] = None
                continue
            signatures[id(node)] = node.operator.compute_output_signature(joined)
        return signatures

    def describe(self) -> str:
        """Return a short topology description.

        Lists inputs, internal nodes (in topological order), and
        outputs. Useful for notebook exploration.
        """
        lines = [
            f"Graph(inputs={list(self.inputs)}, outputs={list(self.outputs)})",
            "  internal nodes (topological order):",
        ]
        for i, node in enumerate(self._order):
            op_name = type(node.operator).__name__ if node.operator else "Input"
            lines.append(f"    [{i}] {op_name}")
        return "\n".join(lines)

compute_output_signature(input_signature: Any) -> Any

None: a graph returns a dict of outputs, not one carrier.

Use output_signatures for each output's signature, and summary for the whole table.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
def compute_output_signature(self, input_signature: Any) -> Any:
    """``None``: a graph returns a dict of outputs, not one carrier.

    Use `output_signatures` for each output's signature, and
    `summary` for the whole table.
    """
    return None

describe() -> str

Return a short topology description.

Lists inputs, internal nodes (in topological order), and outputs. Useful for notebook exploration.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
def describe(self) -> str:
    """Return a short topology description.

    Lists inputs, internal nodes (in topological order), and
    outputs. Useful for notebook exploration.
    """
    lines = [
        f"Graph(inputs={list(self.inputs)}, outputs={list(self.outputs)})",
        "  internal nodes (topological order):",
    ]
    for i, node in enumerate(self._order):
        op_name = type(node.operator).__name__ if node.operator else "Input"
        lines.append(f"    [{i}] {op_name}")
    return "\n".join(lines)

from_config(config: dict[str, Any]) -> Self classmethod

Rebuild a graph from the topology get_config records.

Re-creates each Input, then calls each node's operator on its parents in the recorded order, which wires the nodes exactly as they were; an operator shared by several nodes stays one object.

Parameters:

Name Type Description Default
config dict[str, Any]

A get_config record whose operators have already been rebuilt into Operator instances.

required

Raises:

Type Description
ValueError

if a reference names an undeclared input or a node that comes later in the order.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
@classmethod
def from_config(cls, config: dict[str, Any]) -> Self:
    """Rebuild a graph from the topology `get_config` records.

    Re-creates each `Input`, then calls each node's operator on its
    parents in the recorded order, which wires the nodes exactly as
    they were; an operator shared by several nodes stays one object.

    Args:
        config: A `get_config` record whose ``operators`` have already
            been rebuilt into `Operator` instances.

    Raises:
        ValueError: if a reference names an undeclared input or a node
            that comes later in the order.
    """
    inputs = {name: Input(name) for name in config["inputs"]}
    operators: list[Operator] = config["operators"]
    built: list[Node] = []

    def lookup(ref: dict[str, Any]) -> Node:
        if "input" in ref:
            if ref["input"] not in inputs:
                raise ValueError(f"Graph config: undeclared input {ref!r}.")
            return inputs[ref["input"]]
        index = ref["node"]
        if not 0 <= index < len(built):
            raise ValueError(f"Graph config: {ref!r} is not an earlier node.")
        return built[index]

    for spec in config["nodes"]:
        parents = [lookup(ref) for ref in spec["parents"]]
        built.append(operators[spec["operator"]](*parents))
    outputs = {name: lookup(ref) for name, ref in config["outputs"].items()}
    return cls(inputs=inputs, outputs=outputs)

get_config() -> dict[str, Any]

The whole topology: inputs, operators, nodes and outputs.

Every node is recorded, upstream ones included, so two graphs that differ anywhere have different configs (and so different state records and content hashes). The record::

{
    "inputs": ["image", "reference"],
    "operators": [<state>, ...],
    "nodes": [{"operator": 0, "parents": [{"input": "image"}]}, ...],
    "outputs": {"ndvi": {"node": 0}, "raw": {"input": "image"}},
}

operators lists each distinct operator once, by identity, in first-use order, so an operator shared by several nodes is not duplicated. nodes is in topological order; a parent or an output refers either to a declared input by name or to an earlier node by index.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
def get_config(self) -> dict[str, Any]:
    """The whole topology: inputs, operators, nodes and outputs.

    Every node is recorded, upstream ones included, so two graphs
    that differ anywhere have different configs (and so different
    `state` records and content hashes). The record::

        {
            "inputs": ["image", "reference"],
            "operators": [<state>, ...],
            "nodes": [{"operator": 0, "parents": [{"input": "image"}]}, ...],
            "outputs": {"ndvi": {"node": 0}, "raw": {"input": "image"}},
        }

    ``operators`` lists each distinct operator once, by identity, in
    first-use order, so an operator shared by several nodes is not
    duplicated. ``nodes`` is in topological order; a parent or an
    output refers either to a declared input by name or to an
    earlier node by index.
    """
    input_names = {id(node): name for name, node in self.inputs.items()}
    node_index = {id(node): i for i, node in enumerate(self._order)}
    operator_index: dict[int, int] = {}
    operators: list[dict[str, Any]] = []
    nodes: list[dict[str, Any]] = []

    def ref(node: Node) -> dict[str, Any]:
        if id(node) in input_names:
            return {"input": input_names[id(node)]}
        return {"node": node_index[id(node)]}

    for node in self._order:
        assert node.operator is not None  # guaranteed by _topological_sort
        op_id = id(node.operator)
        if op_id not in operator_index:
            operator_index[op_id] = len(operators)
            operators.append(node.operator.state)
        parents = [ref(parent) for parent in node.parents]
        nodes.append({"operator": operator_index[op_id], "parents": parents})

    return {
        "inputs": list(self.inputs),
        "operators": operators,
        "nodes": nodes,
        "outputs": {name: ref(node) for name, node in self.outputs.items()},
    }

output_signatures(input_signatures: Any) -> dict[str, Any]

Each output's signature, propagated node by node without data.

Parameters:

Name Type Description Default
input_signatures Any

{input name: Signature}; a missing name means unknown. A single-input graph also takes the bare signature.

required

Returns:

Type Description
``{output name

Signature | None};None`` where an

dict[str, Any]

operator does not track shape, or where a multi-input node's

dict[str, Any]

inputs disagree (see summary).

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
def output_signatures(self, input_signatures: Any) -> dict[str, Any]:
    """Each output's signature, propagated node by node without data.

    Args:
        input_signatures: ``{input name: Signature}``; a missing name
            means unknown. A single-input graph also takes the bare
            signature.

    Returns:
        ``{output name: Signature | None}``; ``None`` where an
        operator does not track shape, or where a multi-input node's
        inputs disagree (see `summary`).
    """
    signatures = self._node_signatures(input_signatures)
    return {name: signatures[id(node)] for name, node in self.outputs.items()}

summary(input_signatures: Any = None) -> str

A Keras-style table of the nodes, their input and output signatures.

Nodes are listed in topological order. Signatures propagate through each node's compute_output_signature; a node with several inputs gets its operator's signature for them only when they all agree (an elementwise join), and ? otherwise, since compute_output_signature takes one input. The outputs follow.

Parameters:

Name Type Description Default
input_signatures Any

As for output_signatures; None lists the structure with every signature unknown.

None
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/core/_graph.py
def summary(self, input_signatures: Any = None) -> str:
    """A Keras-style table of the nodes, their input and output signatures.

    Nodes are listed in topological order. Signatures propagate
    through each node's `compute_output_signature`; a node with
    several inputs gets its operator's signature for them only when
    they all agree (an elementwise join), and ``?`` otherwise, since
    `compute_output_signature` takes one input. The outputs follow.

    Args:
        input_signatures: As for `output_signatures`; ``None`` lists
            the structure with every signature unknown.
    """
    signatures = self._node_signatures(input_signatures)
    names = {id(node): name for name, node in self.inputs.items()}

    def label(node: Node) -> str:
        if id(node) in names:
            return names[id(node)]
        return f"[{self._order.index(node)}]"

    def show(signature: Any) -> str:
        if signature is None:
            return "?"
        # a Signature's compact "(y=64, x=64) float32" form
        fmt = getattr(signature, "format", None)
        return fmt() if callable(fmt) else repr(signature)

    rows: list[tuple[str, str, str]] = []
    for i, node in enumerate(self._order):
        parents = ", ".join(label(parent) for parent in node.parents)
        sig_in = ", ".join(show(signatures[id(p)]) for p in node.parents) or "-"
        name = f"[{i}] {type(node.operator).__name__}({parents})"
        rows.append((name, sig_in, show(signatures[id(node)])))
    for out_name, node in self.outputs.items():
        rows.append(
            (f"→ {out_name} = {label(node)}", "", show(signatures[id(node)]))
        )

    w_name = max([len("Node"), *(len(r[0]) for r in rows)])
    w_in = max([len("Input sig"), *(len(r[1]) for r in rows)])
    header = f"{'Node'.ljust(w_name)}  {'Input sig'.ljust(w_in)}  Output sig"
    body = [f"{n.ljust(w_name)}  {i.ljust(w_in)}  {o}" for n, i, o in rows]
    return "\n".join([header, "-" * len(header), *body])

pipekit_ops.Fanout

Bases: Operator

Apply each named operator to the same input; return a dict of outputs.

The dict-keyed companion to juxt. Each operator runs on the same carrier; the results are collected under their keys.

Parameters:

Name Type Description Default
branches dict[str, Operator]

Mapping from output name to Operator.

required

Raises:

Type Description
TypeError

if any branch isn't an Operator.

ValueError

if branches is empty.

Example::

rgb = Fanout({
    "red":   SelectBand(0),
    "green": SelectBand(1),
    "blue":  SelectBand(2),
})
out = rgb(image)
# {"red": ..., "green": ..., "blue": ...}
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_combine.py
class Fanout(Operator):
    """Apply each named operator to the same input; return a dict of outputs.

    The dict-keyed companion to `juxt`. Each operator runs on the same
    carrier; the results are collected under their keys.

    Args:
        branches: Mapping from output name to `Operator`.

    Raises:
        TypeError: if any branch isn't an `Operator`.
        ValueError: if ``branches`` is empty.

    Example::

        rgb = Fanout({
            "red":   SelectBand(0),
            "green": SelectBand(1),
            "blue":  SelectBand(2),
        })
        out = rgb(image)
        # {"red": ..., "green": ..., "blue": ...}
    """

    __config_mixin_auto__ = False  # custom config — nested operators

    def __init__(self, branches: dict[str, Operator]) -> None:
        if not branches:
            raise ValueError("Fanout requires at least one branch.")
        for name, op in branches.items():
            require_operator(op, "Fanout", f"branches[{name!r}]")
        self.branches = dict(branches)

    def _apply(self, x: Any) -> dict[str, Any]:
        return {name: op(x) for name, op in self.branches.items()}

    def get_config(self) -> dict[str, Any]:
        return {
            "branches": {name: nested_config(op) for name, op in self.branches.items()}
        }

    def compute_output_signature(self, input_signature: Any) -> Any:
        """``None``: the output is a dict of branches, not one carrier."""
        return None

    def __repr__(self) -> str:
        names = ", ".join(self.branches)
        return f"Fanout([{names}])"

compute_output_signature(input_signature: Any) -> Any

None: the output is a dict of branches, not one carrier.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_combine.py
def compute_output_signature(self, input_signature: Any) -> Any:
    """``None``: the output is a dict of branches, not one carrier."""
    return None

Inference

geoops.learn.ModelOp

Bases: Operator

Wrap any callable as an Operator.

Materialises the GeoArray to a plain np.ndarray (via np.asarray) before handing it to the model — frameworks that strip the subclass (torch, JAX, sklearn) don't care, and frameworks that preserve it (numpy proper) still see something sensible.

Output contract: the model's return value is passed through as-is and never rewrapped into the input carrier -- a GeoArray input yields whatever the model returns (an np.ndarray, a torch tensor, ...) without transform / crs / fill_value. Rewrap it yourself, or use :class:SklearnOp, which restores the grid for per-pixel estimators.

Parameters:

Name Type Description Default
model Any

Any object that can be called as model(arr) or whose method attribute can be called as model.predict(arr). No framework imports; the shape is checked structurally at construction.

required
method str

Method name to invoke on model. Default "__call__" — equivalent to model(arr). Set to "predict" for sklearn estimators; the model must then satisfy :class:pipekit_ops.Predictor.

'__call__'
batch_size int | None

If set, split the input along axis 0 into chunks of this size, call the model once per chunk, concatenate the results along axis 0. Useful when the model can't fit the whole input in GPU memory.

None

Raises:

Type Description
TypeError

At construction, when method="predict" and model is not a :class:pipekit_ops.Predictor, when method="__call__" and model is not callable, or when model has no callable method attribute.

Note

forbid_in_yaml = True — the model is a runtime object and won't round-trip to YAML. Users typically pin a model artifact (state-dict + class config) themselves.

Examples:

A scikit-learn estimator sees the raw array, so feed it the (n_samples, n_features) table it was fit on; for per-pixel prediction on a (C, H, W) scene use :class:SklearnOp, which flattens the pixels and restores the grid::

op = ModelOp(model=rf_clf, method="predict")
labels = op(features)  # features: (n_samples, n_features)

Batched inference with a torch model::

op = ModelOp(model=unet_model, batch_size=8)
preds = op(chips_gt)  # iterates 8 chips at a time
Source code in packages/geotoolz-ops/src/geoops/learn/_src/operators.py
class ModelOp(Operator):
    """Wrap any callable as an Operator.

    Materialises the GeoArray to a plain ``np.ndarray`` (via
    ``np.asarray``) before handing it to the model — frameworks that
    strip the subclass (torch, JAX, sklearn) don't care, and frameworks
    that preserve it (numpy proper) still see something sensible.

    Output contract: the model's return value is passed through **as-is**
    and never rewrapped into the input carrier -- a ``GeoArray`` input
    yields whatever the model returns (an ``np.ndarray``, a torch tensor,
    ...) without ``transform`` / ``crs`` / ``fill_value``. Rewrap
    it yourself, or use :class:`SklearnOp`, which restores the grid for
    per-pixel estimators.

    Args:
        model: Any object that can be called as ``model(arr)`` or whose
            ``method`` attribute can be called as
            ``model.predict(arr)``. No framework imports; the shape is
            checked structurally at construction.
        method: Method name to invoke on ``model``. Default
            ``"__call__"`` — equivalent to ``model(arr)``. Set to
            ``"predict"`` for sklearn estimators; the model must then
            satisfy :class:`pipekit_ops.Predictor`.
        batch_size: If set, split the input along axis 0 into chunks of
            this size, call the model once per chunk, concatenate the
            results along axis 0. Useful when the model can't fit the
            whole input in GPU memory.

    Raises:
        TypeError: At construction, when ``method="predict"`` and
            ``model`` is not a :class:`pipekit_ops.Predictor`, when
            ``method="__call__"`` and ``model`` is not callable, or when
            ``model`` has no callable ``method`` attribute.

    Note:
        ``forbid_in_yaml = True`` — the model is a runtime object and
        won't round-trip to YAML. Users typically pin a model artifact
        (state-dict + class config) themselves.

    Examples:
        A scikit-learn estimator sees the raw array, so feed it the
        ``(n_samples, n_features)`` table it was fit on; for per-pixel
        prediction on a ``(C, H, W)`` scene use :class:`SklearnOp`,
        which flattens the pixels and restores the grid::

            op = ModelOp(model=rf_clf, method="predict")
            labels = op(features)  # features: (n_samples, n_features)

        Batched inference with a torch model::

            op = ModelOp(model=unet_model, batch_size=8)
            preds = op(chips_gt)  # iterates 8 chips at a time
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # any model: unknown until configured
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space", "time"}, reach=None
    )

    forbid_in_yaml: ClassVar[bool] = True
    # ConfigMixin would auto-derive `model` from `__init__` as a non-JSON
    # opaque object; override with a curated debug repr below.
    __config_mixin_auto__: ClassVar[bool] = False

    def __init__(
        self,
        *,
        model: Any,
        method: str = "__call__",
        batch_size: int | None = None,
    ) -> None:
        if method == "predict":
            if not isinstance(model, Predictor):
                raise TypeError(
                    f'ModelOp(method="predict") needs a pipekit Predictor (an '
                    f"object with a predict method); got {type(model).__name__}"
                )
        elif method == "__call__":
            if not callable(model):
                raise TypeError(
                    f"ModelOp model must be callable; got {type(model).__name__}"
                )
        elif not callable(getattr(model, method, None)):
            raise TypeError(
                f"ModelOp model {type(model).__name__} has no callable "
                f"{method!r} method"
            )
        self.model = model
        self.method = method
        self.batch_size = batch_size

    def _resolve_callable(self) -> Any:
        if self.method == "__call__":
            return self.model
        return getattr(self.model, self.method)

    def _apply(self, gt: Carrier) -> Any:
        reject_geotensor(gt, type(self).__name__)
        arr = np.asarray(gt)
        fn = self._resolve_callable()
        if self.batch_size is None:
            return fn(arr)
        return self._batched(fn, arr)

    def _batched(self, fn: Any, arr: np.ndarray) -> np.ndarray:
        """Split ``arr`` along axis 0, call ``fn`` per chunk, concatenate.

        Plain ``np.concatenate`` along axis 0 — works when the model's
        output preserves the batch dimension (the common case).

        Empty inputs (``arr.shape[0] == 0``) are passed straight to the
        model in one call: ``np.concatenate`` cannot accept an empty list
        of chunks, and the model is free to return a meaningful
        zero-length result.
        """
        n = arr.shape[0]
        if n == 0:
            return fn(arr)
        chunks: list[Any] = []
        bs = int(self.batch_size or n)
        for start in range(0, n, bs):
            chunks.append(fn(arr[start : start + bs]))
        return np.concatenate(chunks, axis=0)

    def get_config(self) -> dict[str, Any]:
        return {
            "model_type": type(self.model).__name__,
            "method": self.method,
            "batch_size": self.batch_size,
        }

Observers — identity with side effects

pipekit_ops.Tap

Bases: Operator

Fire a callback on the carrier; return the carrier unchanged.

Distinct from Sink only by naming convention — Tap is for observation (logging, metrics, breakpoint hooks); Sink is for persistence. Both pass the carrier through; both carry forbid_in_yaml = True.

Parameters:

Name Type Description Default
fn Callable[[Any], Any]

Callable invoked with the carrier. Its return value is ignored.

required
name str | None

Optional name for __repr__. Defaults to the callable's __name__ if available, otherwise "Tap".

None

Example::

log = Tap(lambda x: print(getattr(x, "shape", x)), name="log_shape")
pipe = Scale(2.0) | log | AddConst(1.0)
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/observe/_observers.py
class Tap(Operator):
    """Fire a callback on the carrier; return the carrier unchanged.

    Distinct from `Sink` only by naming convention — `Tap` is for
    observation (logging, metrics, breakpoint hooks); `Sink` is for
    persistence. Both pass the carrier through; both carry
    ``forbid_in_yaml = True``.

    Args:
        fn: Callable invoked with the carrier. Its return value is
            ignored.
        name: Optional name for ``__repr__``. Defaults to the
            callable's ``__name__`` if available, otherwise ``"Tap"``.

    Example::

        log = Tap(lambda x: print(getattr(x, "shape", x)), name="log_shape")
        pipe = Scale(2.0) | log | AddConst(1.0)
    """

    forbid_in_yaml: ClassVar[bool] = True
    __config_mixin_auto__ = False

    def __init__(self, fn: Callable[[Any], Any], name: str | None = None) -> None:
        self.fn = fn
        self.name = name or getattr(fn, "__name__", "Tap")
        self._warned_traced = False

    def _apply(self, x: Any) -> Any:
        if not self._warned_traced and is_traced(x):
            self._warned_traced = True
            warnings.warn(
                f"Tap {self.name!r} is running at trace time, so it fires once "
                "per compilation and sees a tracer. Use jax.debug.callback to "
                "observe values on every call.",
                UserWarning,
                stacklevel=2,
            )
        self.fn(x)
        return x

    def get_config(self) -> dict[str, Any]:
        return {"name": self.name}

    def __repr__(self) -> str:
        return f"Tap(name={self.name!r})"

pipekit_ops.Snapshot

Controller that captures intermediate carriers by name.

Not an Operator itself. Call .at(key) to obtain a per-step operator that stores the carrier under that key.

Attributes:

Name Type Description
captures dict[str, Any]

Dict {key: last-seen carrier}. Repeated keys overwrite — the most recent value wins.

Example::

snap = Snapshot()
pipe = snap.at("pre") | Scale(2.0) | snap.at("post") | AddConst(1.0)
pipe(3.0)
snap.captures
# {"after_scale": 3.0, "after_add": 6.0}
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/observe/_observers.py
class Snapshot:
    """Controller that captures intermediate carriers by name.

    Not an `Operator` itself. Call ``.at(key)`` to obtain a per-step
    operator that stores the carrier under that key.

    Attributes:
        captures: Dict ``{key: last-seen carrier}``. Repeated keys
            overwrite — the most recent value wins.

    Example::

        snap = Snapshot()
        pipe = snap.at("pre") | Scale(2.0) | snap.at("post") | AddConst(1.0)
        pipe(3.0)
        snap.captures
        # {"after_scale": 3.0, "after_add": 6.0}
    """

    def __init__(self) -> None:
        self.captures: dict[str, Any] = {}

    def at(self, key: str) -> Operator:
        return _SnapshotAt(self, key)

    def clear(self) -> None:
        self.captures.clear()

    def __repr__(self) -> str:
        return f"Snapshot(keys={list(self.captures)!r})"

pipekit_ops.ShapeTrace

Bases: Operator

Log shape / dtype of each carrier passing through.

Parameters:

Name Type Description Default
printer Callable[[str], None]

Callable invoked with the formatted line. Defaults to the built-in print.

print
mode str

"every" logs every call; "diff_only" logs only when the (shape, dtype) tuple changes from the previous call. "diff_only" is the typical notebook mode.

'every'
label str | None

Optional prefix for the printed line (useful when multiple ShapeTrace instances co-exist in one pipeline).

None
extra Callable[[Any], str | None] | None

Optional callable carrier -> str | None whose result is printed as a second, indented line: what a carrier carries besides shape and dtype (a coordinate system, units). None or "" prints nothing. In "diff_only" mode a change in it counts as a change.

None

Example::

trace = ShapeTrace(mode="diff_only", label="post-resample")
pipe = Resample() | trace | NDVI()

# print the coordinate system too
ShapeTrace(extra=lambda gt: f"crs={gt.crs}")
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/observe/_observers.py
class ShapeTrace(Operator):
    """Log ``shape`` / ``dtype`` of each carrier passing through.

    Args:
        printer: Callable invoked with the formatted line. Defaults to
            the built-in ``print``.
        mode: ``"every"`` logs every call; ``"diff_only"`` logs only
            when the (shape, dtype) tuple changes from the previous
            call. ``"diff_only"`` is the typical notebook mode.
        label: Optional prefix for the printed line (useful when
            multiple `ShapeTrace` instances co-exist in one pipeline).
        extra: Optional callable ``carrier -> str | None`` whose result
            is printed as a second, indented line: what a carrier
            carries besides shape and dtype (a coordinate system,
            units). ``None`` or ``""`` prints nothing. In
            ``"diff_only"`` mode a change in it counts as a change.

    Example::

        trace = ShapeTrace(mode="diff_only", label="post-resample")
        pipe = Resample() | trace | NDVI()

        # print the coordinate system too
        ShapeTrace(extra=lambda gt: f"crs={gt.crs}")
    """

    forbid_in_yaml: ClassVar[bool] = True
    __config_mixin_auto__ = False

    def __init__(
        self,
        printer: Callable[[str], None] = print,
        mode: str = "every",
        label: str | None = None,
        extra: Callable[[Any], str | None] | None = None,
    ) -> None:
        if mode not in ("every", "diff_only"):
            raise ValueError(
                f"ShapeTrace.mode must be 'every' or 'diff_only', got {mode!r}."
            )
        self.printer = printer
        self.mode = mode
        self.label = label
        self.extra = extra
        self._last: tuple[Any, Any, Any] | None = None

    def _apply(self, x: Any) -> Any:
        shape = getattr(x, "shape", None)
        dtype = getattr(x, "dtype", None)
        more = self.extra(x) if self.extra is not None else None
        current = (tuple(shape) if shape is not None else None, dtype, more)
        if self.mode == "diff_only" and current == self._last:
            return x
        self._last = current
        prefix = f"[{self.label}] " if self.label else ""
        self.printer(f"{prefix}shape={current[0]} dtype={current[1]}")
        if more:
            self.printer(f"{prefix}  {more}")
        return x

    def get_config(self) -> dict[str, Any]:
        return {"mode": self.mode, "label": self.label}

    def __repr__(self) -> str:
        return f"ShapeTrace(mode={self.mode!r}, label={self.label!r})"

Control flow

pipekit_ops.Branch

Bases: Operator

Binary conditional: run if_true or if_false based on a predicate.

Parameters:

Name Type Description Default
predicate Callable[..., bool]

Callable carrier → bool. The decision function.

required
if_true Operator

Operator applied when predicate(carrier) is truthy.

required
if_false Operator | None

Operator applied when predicate(carrier) is falsy. Defaults to Identity — the carrier flows through unchanged.

None

Example::

clean_if_dirty = Branch(
    predicate=has_nans,
    if_true=GapFill(),
    if_false=Identity(),
)
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_control.py
class Branch(Operator):
    """Binary conditional: run ``if_true`` or ``if_false`` based on a predicate.

    Args:
        predicate: Callable ``carrier → bool``. The decision function.
        if_true: `Operator` applied when ``predicate(carrier)`` is truthy.
        if_false: `Operator` applied when ``predicate(carrier)`` is falsy.
            Defaults to `Identity` — the carrier flows through unchanged.

    Example::

        clean_if_dirty = Branch(
            predicate=has_nans,
            if_true=GapFill(),
            if_false=Identity(),
        )
    """

    forbid_in_yaml: ClassVar[bool] = True
    __config_mixin_auto__ = False

    def __init__(
        self,
        predicate: Callable[..., bool],
        if_true: Operator,
        if_false: Operator | None = None,
    ) -> None:
        require_operator(if_true, "Branch", "if_true")
        if if_false is not None:
            require_operator(if_false, "Branch", "if_false")
        self.predicate = predicate
        self.if_true = if_true
        self.if_false = if_false if if_false is not None else Identity()

    def _apply(self, x: Any) -> Any:
        return self.if_true(x) if self.predicate(x) else self.if_false(x)

    def get_config(self) -> dict[str, Any]:
        return {
            "predicate": callable_name(self.predicate),
            "if_true": nested_config(self.if_true),
            "if_false": nested_config(self.if_false),
        }

    def compute_output_signature(self, input_signature: Any) -> Any:
        """The signature both branches agree on (else ``None``)."""
        return common_signature(
            self.if_true.compute_output_signature(input_signature),
            self.if_false.compute_output_signature(input_signature),
        )

    def __repr__(self) -> str:
        return (
            f"Branch(predicate={callable_name(self.predicate)}, "
            f"if_true={self.if_true!r}, if_false={self.if_false!r})"
        )

compute_output_signature(input_signature: Any) -> Any

The signature both branches agree on (else None).

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_control.py
def compute_output_signature(self, input_signature: Any) -> Any:
    """The signature both branches agree on (else ``None``)."""
    return common_signature(
        self.if_true.compute_output_signature(input_signature),
        self.if_false.compute_output_signature(input_signature),
    )

pipekit_ops.Switch

Bases: Operator

Multi-way dispatch on key(carrier).

Parameters:

Name Type Description Default
key Callable[..., Hashable]

Callable carrier → hashable. The dispatch key.

required
cases dict[Hashable, Operator]

Mapping from key-value to Operator. Whichever case matches key(carrier) is applied.

required
default Operator | None

Operator for the unmatched case. Defaults to Identity.

None

Example::

by_sensor = Switch(
    key=lambda gt: gt.attrs["sensor"],
    cases={
        "sentinel-2": Sentinel2Pipeline(),
        "landsat-8":  Landsat8Pipeline(),
    },
    default=Identity(),
)
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_control.py
class Switch(Operator):
    """Multi-way dispatch on ``key(carrier)``.

    Args:
        key: Callable ``carrier → hashable``. The dispatch key.
        cases: Mapping from key-value to `Operator`. Whichever case
            matches ``key(carrier)`` is applied.
        default: `Operator` for the unmatched case. Defaults to `Identity`.

    Example::

        by_sensor = Switch(
            key=lambda gt: gt.attrs["sensor"],
            cases={
                "sentinel-2": Sentinel2Pipeline(),
                "landsat-8":  Landsat8Pipeline(),
            },
            default=Identity(),
        )
    """

    forbid_in_yaml: ClassVar[bool] = True
    __config_mixin_auto__ = False

    def __init__(
        self,
        key: Callable[..., Hashable],
        cases: dict[Hashable, Operator],
        default: Operator | None = None,
    ) -> None:
        for k, op in cases.items():
            require_operator(op, "Switch", f"cases[{k!r}]")
        if default is not None:
            require_operator(default, "Switch", "default")
        self.key = key
        self.cases = dict(cases)
        self.default = default if default is not None else Identity()

    def _apply(self, x: Any) -> Any:
        k = self.key(x)
        op = self.cases.get(k, self.default)
        return op(x)

    def get_config(self) -> dict[str, Any]:
        return {
            "key": callable_name(self.key),
            "cases": {str(k): nested_config(op) for k, op in self.cases.items()},
            "default": nested_config(self.default),
        }

    def compute_output_signature(self, input_signature: Any) -> Any:
        """The signature every case and the default agree on (else ``None``)."""
        signatures = [
            op.compute_output_signature(input_signature)
            for op in (*self.cases.values(), self.default)
        ]
        return common_signature(*signatures)

    def __repr__(self) -> str:
        cases = ", ".join(f"{k!r}: {op!r}" for k, op in self.cases.items())
        return (
            f"Switch(key={callable_name(self.key)}, cases={{{cases}}}, "
            f"default={self.default!r})"
        )

compute_output_signature(input_signature: Any) -> Any

The signature every case and the default agree on (else None).

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_control.py
def compute_output_signature(self, input_signature: Any) -> Any:
    """The signature every case and the default agree on (else ``None``)."""
    signatures = [
        op.compute_output_signature(input_signature)
        for op in (*self.cases.values(), self.default)
    ]
    return common_signature(*signatures)

Building blocks

pipekit_ops.Identity

Bases: Operator

Explicit no-op. Returns its input unchanged.

Used as the default value for slots that need an Operator but where "do nothing" is the right behaviour — Branch.if_false, Switch.default, training-mode-off augmentation, etc.

Example::

Branch(predicate=is_clean, if_true=Identity(), if_false=Despeckle())
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_blocks.py
class Identity(Operator):
    """Explicit no-op. Returns its input unchanged.

    Used as the default value for slots that need an `Operator` but
    where "do nothing" is the right behaviour — `Branch.if_false`,
    `Switch.default`, training-mode-off augmentation, etc.

    Example::

        Branch(predicate=is_clean, if_true=Identity(), if_false=Despeckle())
    """

    def _apply(self, x: Any) -> Any:
        return x

pipekit_ops.Const

Bases: Operator

Return a fixed value, ignoring any input.

Useful for test fixtures, Switch default cases that should emit a sentinel, and golden values used in Try fallbacks.

Example::

zero = Const(0.0)
assert zero() == 0.0
assert zero("anything") == 0.0

The value should be JSON-primitive for round-trip via from_state.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_blocks.py
class Const(Operator):
    """Return a fixed value, ignoring any input.

    Useful for test fixtures, `Switch` default cases that should emit a
    sentinel, and golden values used in `Try` fallbacks.

    Example::

        zero = Const(0.0)
        assert zero() == 0.0
        assert zero("anything") == 0.0

    The value should be JSON-primitive for round-trip via `from_state`.
    """

    def __init__(self, value: Any) -> None:
        self.value = value

    def _apply(self, *args: Any, **kwargs: Any) -> Any:
        return self.value

pipekit_ops.Lambda

Bases: Operator

Wrap an arbitrary callable as an Operator.

The escape hatch for one-off operations that don't warrant a named subclass. Carries forbid_in_yaml = True because the wrapped callable typically captures closure state that doesn't survive JSON / YAML round-trip.

Parameters:

Name Type Description Default
fn Callable[..., Any]

The callable to wrap. Receives the carrier and any extra positional / keyword arguments forwarded through __call__.

required
name str | None

Optional name for __repr__. Defaults to the callable's __name__ if available, otherwise "Lambda".

None

Example::

twice = Lambda(lambda x: x * 2, name="double")
assert twice(3) == 6
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_blocks.py
class Lambda(Operator):
    """Wrap an arbitrary callable as an `Operator`.

    The escape hatch for one-off operations that don't warrant a named
    subclass. Carries ``forbid_in_yaml = True`` because the wrapped
    callable typically captures closure state that doesn't survive
    JSON / YAML round-trip.

    Args:
        fn: The callable to wrap. Receives the carrier and any extra
            positional / keyword arguments forwarded through ``__call__``.
        name: Optional name for ``__repr__``. Defaults to the
            callable's ``__name__`` if available, otherwise ``"Lambda"``.

    Example::

        twice = Lambda(lambda x: x * 2, name="double")
        assert twice(3) == 6
    """

    forbid_in_yaml: ClassVar[bool] = True
    __config_mixin_auto__ = False  # auto-config would emit the closure

    def __init__(self, fn: Callable[..., Any], name: str | None = None) -> None:
        self.fn = fn
        self.name = name or getattr(fn, "__name__", "Lambda")

    def _apply(self, *args: Any, **kwargs: Any) -> Any:
        return self.fn(*args, **kwargs)

    def get_config(self) -> dict[str, Any]:
        # Debug-only — closures don't round-trip.
        return {"name": self.name}

    def __repr__(self) -> str:
        return f"Lambda(name={self.name!r})"

pipekit_ops.Sink

Bases: Operator

Apply a side-effecting write and pass the input through unchanged.

The canonical checkpointing primitive: log, persist, broadcast, etc. The return value of write_fn is discarded; the original input flows on.

Sink is not marked _terminal because it returns the carrier — a Sequential can continue past it. For operators that legitimately return None (write-to-disk, render-and-exit), define a subclass with _terminal = True and put it at the end.

Parameters:

Name Type Description Default
write_fn Callable[..., Any]

Callable that consumes the carrier for side effects. Its return value is ignored.

required
name str | None

Optional name for __repr__. Defaults to the callable's __name__ if available, otherwise "Sink".

None

Raises:

Type Description
TypeError

If the carrier is a JAX tracer, for example inside jax.jit. A written tracer is never a value; use Tap with jax.debug.callback to observe values at run time.

Example::

log = Sink(lambda gt: print(gt.shape), name="log_shape")
pipe = Scale(2.0) | log | AddConst(1.0)
# log fires between Scale and AddConst; the carrier is untouched
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/operators/_blocks.py
class Sink(Operator):
    """Apply a side-effecting write and pass the input through unchanged.

    The canonical checkpointing primitive: log, persist, broadcast, etc.
    The return value of ``write_fn`` is discarded; the original input
    flows on.

    `Sink` is **not** marked ``_terminal`` because it returns the
    carrier — a `Sequential` can continue past it. For operators that
    legitimately return ``None`` (write-to-disk, render-and-exit),
    define a subclass with ``_terminal = True`` and put it at the end.

    Args:
        write_fn: Callable that consumes the carrier for side effects.
            Its return value is ignored.
        name: Optional name for ``__repr__``. Defaults to the
            callable's ``__name__`` if available, otherwise ``"Sink"``.

    Raises:
        TypeError: If the carrier is a JAX tracer, for example inside
            ``jax.jit``. A written tracer is never a value; use `Tap` with
            ``jax.debug.callback`` to observe values at run time.

    Example::

        log = Sink(lambda gt: print(gt.shape), name="log_shape")
        pipe = Scale(2.0) | log | AddConst(1.0)
        # log fires between Scale and AddConst; the carrier is untouched
    """

    traceable: ClassVar[bool] = False
    forbid_in_yaml: ClassVar[bool] = True
    __config_mixin_auto__ = False

    def __init__(self, write_fn: Callable[..., Any], name: str | None = None) -> None:
        self.write_fn = write_fn
        self.name = name or getattr(write_fn, "__name__", "Sink")

    def _apply(self, x: Any, /, *args: Any, **kwargs: Any) -> Any:
        if is_traced(x):
            raise TypeError(
                f"Sink {self.name!r} cannot write a traced value inside a JAX "
                "transformation. Use Tap with jax.debug.callback to observe "
                "values at run time."
            )
        self.write_fn(x, *args, **kwargs)
        return x

    def get_config(self) -> dict[str, Any]:
        return {"name": self.name}

    def __repr__(self) -> str:
        return f"Sink(name={self.name!r})"