AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Input and output specs¶
A spec states the kind and structure of a value without holding the value: a term spec declares one value, an input spec declares the inputs of a function or of a conditional distribution, and an output spec declares the outputs of a function or of a draw. A constraint declares the support of a numeric value. The values themselves are on Values and records.
Term specs¶
TermSpec
¶
Bases: ABC
The kind and structure of one value, independent of its label.
Specs are immutable, hashable, and compare by declaration. Symbolic dimensions share a scope through nested schemas and declarations.
is_concrete
property
¶
Whether no symbolic dimensions remain.
free_dims
property
¶
The unbound symbolic dimension names this spec declares.
A spec that declares no shape and holds no schema has none, which is the default. A spec carrying a shape reports its symbolic entries; a spec carrying another schema reports that schema's, so a name is visible wherever it is declared and not only at the outermost level.
The names are what makes a template polymorphic. They live in one scope per template: the same name in two places is one dimension, whether the two places are sibling fields or one inside a term spec's own schema, and binding resolves every occurrence together.
with_dim_sizes(**sizes)
¶
Return a new spec with symbolic dimensions replaced by the supplied sizes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**sizes
|
int
|
Non-negative sizes keyed by dimension name. Unmentioned dimensions stay symbolic; names absent from the spec are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The substituted spec, with other metadata preserved. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a size is not an integer or is a |
ValueError
|
If a size is negative. |
Source code in probpipe/core/_spec_base.py
with_dim_names(**names)
¶
Return a spec with symbolic dimensions renamed simultaneously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**names
|
str
|
Old dimension names mapped to new names, each a Python identifier. Fixed sizes and unrelated metadata are preserved; unknown old names are ignored. Renaming two symbols to one joins their scopes. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The renamed spec. The original is unchanged. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a new name is not a string. |
ValueError
|
If a new name is not a Python identifier. |
Source code in probpipe/core/_spec_base.py
bind_dims_from_value(value)
¶
Unify against a value and return the resulting spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value supplying actual dimensions. All occurrences of a symbol must agree within this spec. Missing callable declarations leave their dimensions symbolic. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A spec with the observed dimensions bound; no input is mutated. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If kinds, structure, or repeated dimension sizes disagree. |
Source code in probpipe/core/_spec_base.py
bind_dims_from_spec(other)
¶
Unify against another declaration and return the resulting spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
TermSpec
|
The spec to unify with, in one scope: a symbolic dimension on either side binds to the size the other side gives at its axis, and a name both sides declare is one dimension, which may stay free. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
This declaration with sizes learned from the other spec. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the argument is not a spec. |
ValueError
|
If kinds, structure, or repeated sizes disagree, or two different
symbolic dimensions meet at one axis, which |
Source code in probpipe/core/_spec_base.py
is_valid(value)
abstractmethod
¶
Whether value is a valid value for this spec.
Each concrete spec checks everything it declares; see its own
is_valid docstring for the exact conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The concrete value to check against this spec. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in probpipe/core/_spec_base.py
NumericSpec
¶
Bases: TermSpec
A spec whose values have a flat numeric layout; this adds no kind.
Subclasses implement _vector_size for concrete specs. The public
vector_size property rejects unbound dimensions before calling it.
vector_size
property
¶
The number of scalar coordinates in one value's flat numeric vector.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the spec still has symbolic dimensions. The message lists the dimensions that must first be made concrete. |
NumericArraySpec(shape, dtype=None, support=None)
dataclass
¶
Bases: NumericSpec
A numeric-array value spec: an event shape plus optional metadata.
dtype and support are optional (default None); when unset the
spec describes its shape only. Each dimension is either a fixed
non-negative integer or a symbolic dimension name, which is a Python
identifier such as n_obs. Repeated names must have the same size when a
value is validated. dtype accepts any numpy.dtype
spelling (a dtype instance, a scalar type such as jnp.float32, or a
string such as "float32") and is normalised to numpy.dtype at
construction, so equal dtypes compare and hash equal however they were
spelled. A spec with dtype=None is not equal to one with a
concrete dtype. support must be hashable when set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
int, str, or sequence of int or str
|
The event shape, which holds one dimension per axis and is stored as a
tuple. A single int or str is one dimension: |
required |
dtype
|
dtype - like
|
The dtype of the values. Stored as a |
None
|
support
|
Constraint
|
The constraint the entries of a value satisfy. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If shape is not an int, a str, or an iterable of them, or a dimension
is a |
ValueError
|
If a dimension is a negative integer or a name that is not a Python identifier. |
Source code in probpipe/core/_spec_base.py
free_dims
property
¶
The symbolic entries of shape.
__repr__()
¶
The shape, then the dtype and the support where they are set.
Source code in probpipe/core/_spec_base.py
is_valid(value)
¶
Whether value is a numeric array (or scalar) matching this spec.
Checks that value is a numeric array-like (a numeric Python scalar,
or an object with a numeric dtype and a shape) whose shape
has the declared rank and fixed sizes (a numeric scalar has shape
()), with repeated symbolic dimensions agreeing, and whose
dtype is same-kind castable to dtype when set — a widening
promotion (e.g. float32 for a float64 spec) or a within-kind
narrowing both pass, while a cross-kind conversion (e.g. a float where
an integer dtype is declared) does not (a bare Python scalar reports
the dtype np.asarray gives it). Strings, mappings, Python
lists/tuples, and non-numeric arrays are invalid. Never raises on a
mismatched value — a value the spec does not describe returns
False.
support is not checked here. Unlike shape and dtype it is a
data-dependent, element-wise check that cannot run under jax.jit
tracing, and is_valid is the check Record construction runs
(which happens inside traces). support is therefore descriptive
metadata on the spec; is_valid validates structure only and so
runs under jax.jit unchanged.
Source code in probpipe/core/_spec_base.py
OpaqueSpec(type=None, meta=None)
dataclass
¶
Bases: TermSpec
The fallback value spec, for a value no other spec describes.
An opaque value carries no exposed structure, as a string, a DataFrame, or an arbitrary Python object does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type
|
type or None
|
The Python type of the values the spec admits, which |
None
|
meta
|
Hashable
|
Free-form metadata, such as units or a tag. It is part of the spec's
equality and hash, and it is never checked against a value or inferred,
so |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If type is neither a class nor |
is_valid(value)
¶
Whether value is a valid opaque value: an instance of type, and no mapping.
A Mapping denotes tree structure, a subtree rather than a leaf, so no
opaque spec admits one. With no type every other value is valid,
including a numeric array or scalar, which a NumericArraySpec
typically describes but an explicitly opaque field still accepts.
meta is not checked against the value.
Notes
The record layer honours the same rule: mappings are never leaves, so
Record construction materialises a mapping field
value into a nested subtree.
Source code in probpipe/core/_spec_base.py
__repr__()
¶
The type and the metadata where they are set, so an open spec reads OpaqueSpec().
RecordSpec(_field_specs=None, /, **field_specs)
¶
Bases: NamedTree[TermSpec], Immutable, TermSpec
Structural description of a value: its named, possibly-nested leaf structure.
A RecordSpec describes the structure of a value as a named
tree — an insertion-ordered map of named fields whose only internal node
is a nested RecordSpec and whose leaves are value specs. It is the
schema of a Record (the value type with the same
named-tree shape), not a description of an arbitrary JAX PyTree (see
Terminology and JAX pytree contract below).
The word event follows probabilistic-programming usage and generalizes
the event / event_shape notion from other PPLs (TensorFlow
Probability, distrax, NumPyro). There, event_shape is the shape of a
single draw of one array-valued random variable. ProbPipe supports
distributions over general value types, not just arrays. The event in this
context can thus be a structured Python object, with structure described by
the RecordSpec.
Conformance and unification require the same field order at every record
level. A raw mapping may list its keys in another order; function and kernel
boundaries lay it out in declaration order before passing it to a body.
An existing record in another order is refused with ValueError.
Terminology. Used precisely throughout this class:
- field — one named object in the collection (here, a value spec),
addressed by its
/-delimited path from the root, such as"physics/mass", or a single name for a flat template.keys,values,items, iteration, andlenrange over the fields, keyed by path. - leaf — a terminal node: a
TermSpec. A nestedRecordSpecis a group, not a leaf; the fields are the leaves. - indexing —
[]takes a path or a list of paths, asNamedTreestates: one path gives the spec at that node, a value spec or a group'sRecordSpec, and a list of paths gives the template cut down to those nodes, each at its own path.p in templateholds for the path of a field or a group. The same paths index a template or the value it describes (template["physics"]/record["physics"]); this collection protocol is shared withRecord. - canonical leaf order — the order in which leaves are traversed:
depth-first, following each level's insertion order. This is the single
ordering every leaf-wise operation uses.
keysis its canonical definition — it returns the key (path) of every leaf in this order; the value-levelto_vectorandfrom_vectorlay out and read leaves in it, andleaf_shapesis keyed by it.
JAX pytree contract. A RecordSpec is not a registered JAX pytree node —
its value specs are atomic, so jax.tree_util.tree_leaves(template) == [template].
It is the schema of the value pytrees it describes, not a pytree itself (think of
it as an enriched PyTreeDef that also carries each leaf's kind / shape).
For a value v it describes (a Record): a nested
RecordSpec mirrors a nested Record (both internal nodes), and each
value spec mirrors one field value. When every leaf is an array (the
NumericRecordSpec / NumericRecord case),
jax.tree_util.tree_leaves(v) returns the leaves in keys
order. The one place the template's leaves and JAX's diverge is an
OpaqueSpec leaf whose value is itself a JAX container (a tuple
/ list; a dict is never a leaf — mappings denote tree structure):
the template counts it as a single leaf while JAX descends into it. See
Record for the full statement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_field_specs
|
Mapping or RecordSpec
|
The fields as a positional mapping, keyed by name or by |
None
|
**field_specs
|
tuple, TermSpec, or Mapping
|
Fields with non-empty names. Each value is one of:
|
{}
|
Examples:
::
RecordSpec(x=(), y=(3,)) # -> NumericRecordSpec
RecordSpec(label=OpaqueSpec(), x=()) # -> RecordSpec (mixed)
RecordSpec(physics=RecordSpec(force=(), mass=()), obs=())
Notes
Inspired by JAX's PyTreeDef: a template can reconstruct a value from its
leaves and describes the expected structure for type-checking and
vectorization. Leaves are stored as frozen, hashable spec objects, so a
template is itself hashable (usable as a jit / treedef cache key).
__getitem__ at a field's path returns the stored value spec, and at a
group's path the group's RecordSpec (see Terminology); the
enumeration of leaves is keys, and per-leaf array shapes (on a
numeric template) live on leaf_shapes.
Symbolic array dimensions make a template polymorphic. free_dims
returns their names and is_concrete is true only when all dimensions
are fixed. Function invocation binds symbols in a call-local scope rather
than mutating the declaration.
Calling RecordSpec(...) directly auto-promotes to a
NumericRecordSpec when every spec is numeric (and every nested
sub-template is itself all-numeric), so vector_size and
leaf_shapes are reachable in the common all-numeric case
without naming the subclass. Mixed templates (any opaque / None spec)
stay plain RecordSpec and do not expose vector_size — it is
not a meaningful quantity once opaque leaves are present.
Empty subtrees in a numeric parent are normalized to NumericRecordSpec
and contribute zero coordinates. A standalone RecordSpec() stays plain.
Source code in probpipe/core/_record_spec.py
is_numeric
property
¶
Whether every reachable leaf implements NumericSpec.
Nested record schemas are checked recursively. Opaque, distribution, and callable leaves are non-numeric unless their spec implements the numeric mixin. The empty schema has no non-numeric leaves.
free_dims
property
¶
Symbolic dimension names declared anywhere in this template.
is_concrete
property
¶
Whether every dimension this template declares has a fixed size.
is_valid(value)
¶
Whether a record or raw mapping satisfies the complete schema.
Fields must match exactly, including the order of an existing record. Raw mappings may list keys in any order. Nested structure, kinds, shapes and declared dtypes are checked, including agreement of repeated symbolic sizes. Structural mismatches return False; unexpected inspection errors propagate.
Source code in probpipe/core/_record_spec.py
numeric_subset()
¶
Project to the NumericSpec-leaf sub-template.
Keeps every numeric leaf and drops non-numeric leaves and empty
subtrees. Surviving leaves retain their metadata, canonical order and
/-delimited paths.
The projection is idempotent. An all-numeric template without empty
subtrees produces an equal NumericRecordSpec.
Returns:
| Type | Description |
|---|---|
NumericRecordSpec
|
The numeric-leaf sub-template, so that |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no numeric leaves survive. The message names the dropped fields. |
Source code in probpipe/core/_record_spec.py
infer_from(value)
classmethod
¶
Best-effort, lossy schema inferred by inspecting a value.
Two cases:
- A
Recordalready carries its authoritative schema, soinfer_fromreturns itsevent_templateunchanged. - A mapping of named fields (e.g. a
Record's field dict) is inferred field by field: a nestedRecordfield contributes its own schema; other tracked fields, distributions included, retain their specs. Callables become function specs; a numeric array or scalar becomes aNumericArraySpecof its shape, and a remaining raw value becomes theOpaqueSpecof its type. The result auto-promotes to aNumericRecordSpecwhen every field is numeric.
This is the fallback for wrapping a raw value that has no template
yet (e.g. at a workflow boundary); for a value you already hold, read
its authoritative event_template directly. Inference is lossy — it
cannot recover an untracked array's declared dtype / support
constraints or opaque metadata. A tracked field keeps its own spec.
A Python list /
tuple leaf (no .shape / .dtype) is treated as opaque even if
it holds numbers; wrap it in
np.asarray / jnp.asarray first for a numeric leaf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
A |
required |
Returns:
| Type | Description |
|---|---|
RecordSpec
|
The inferred schema (a |
Raises:
| Type | Description |
|---|---|
TypeError
|
If value is neither a |
Source code in probpipe/core/_record_spec.py
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | |
__repr__()
¶
Each child by name, as the constructor takes it.
A bare array spec, which declares only a shape, renders as its shape-tuple shorthand, which the constructor accepts.
Source code in probpipe/core/_record_spec.py
NumericRecordSpec(_field_specs=None, /, **field_specs)
¶
Bases: RecordSpec, NumericSpec
RecordSpec where every leaf is numeric.
Extends RecordSpec by requiring every leaf to implement
NumericSpec. Shape tuples remain shorthand for array specs,
and nested numeric records retain their structure. That restriction is what makes
vector_size and leaf_shapes meaningful:
vector_size is the length of the per-element 1-D vector — the total
number of scalar elements across every numeric leaf — and
from_vector takes a template of this class
so that every field can be reconstructed from a slice of that vector. A
batch of such values is a matrix of shape (*batch_shape, vector_size),
not a single vector.
Use RecordSpec.infer_from on a NumericRecord
(it auto-promotes) or call this constructor directly when you have
the shape specs in hand.
Source code in probpipe/core/_record_spec.py
leaf_shapes
property
¶
Per-leaf array shapes, keyed by keys (canonical leaf order).
Array leaves retain their declared shape, including symbolic entries.
Nested records contribute one entry per leaf. Other numeric kinds
contribute their flat coordinate shape, (vector_size,); they must
be concrete for that size to be available. General mixed schemas have
no numeric layout and expose only their structural keys.
is_concrete
property
¶
Whether no symbolic dimension remains, as TermSpec defines it.
Read from the layout cached at construction, which is populated exactly when every dimension was concrete.
BatchSpec(element, levels=None, /, **level_shapes)
dataclass
¶
Bases: TermSpec
A term spec for a Batch: an element spec plus a named multiplicity.
BatchSpec(element, **levels) declares a batch whose elements are described
by element, with one keyword per level mapping the level's name to the
shape of its axes, outermost level first::
BatchSpec(NumericArraySpec(()), chain=4, draw=1000)
BatchSpec(NumericArraySpec(()), grid=(3, 4)) # one level of two axes
BatchSpec(NumericArraySpec(("n",)), draw="S") # S draws, S unbound
BatchSpec(OpaqueSpec(), {"my level": 2}) # a name no keyword spells
Each level's shape is read as NumericArraySpec reads shape, so a
single int or str is one axis: draw=4 is draw=(4,). A level name that
cannot be written as a keyword argument, such as "my level" or
"class", is given in a mapping passed positionally instead, and the two
forms are not combined. levels
returns the mapping, so BatchSpec(other_spec, batch.spec.levels) declares
another element type over the same levels.
element_spec is the output spec of one element: its spec,
element_spec.term_spec, and its outputs. A bare spec given as element
takes the raw default: a single array or opaque value names the elements
"element", as OutputSpec(element=NumericArraySpec(())), and a record, a
distribution, a conditional distribution, or a batch of records or of
distributions is in the positional form, as OutputSpec(RecordSpec(...)).
For now a function's spec, and the spec of a batch of single arrays or
opaque values, also name the elements "element", since the positional
form does not take them yet. The repr leaves the raw default's name out.
The stored form is axis_groups and level_names: the batch
axes tiled into named levels as Batch describes them. Level names
are unique within a batch, and batch_shape / batch_size read off the
tiling.
This is the single stored source of a batch's type, so it specifies the
collection rather than one element, and Batch keeps no second copy
of the multiplicity: its shape and level accessors read the stored spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element
|
OutputSpec or TermSpec
|
The output spec of one element, or the spec every element satisfies, including numeric-array and opaque kinds, which takes the raw default. Positional-only. |
required |
levels
|
Mapping of str to shape
|
The levels as a mapping from level name to shape, outermost first. Positional-only, and given only when no level is given as a keyword. |
None
|
**level_shapes
|
int, str, or sequence of int or str
|
The levels as keywords, outermost first, each mapping a level name to the
shape of its axes. A level name follows the rule for output names, so
it is any non-empty string without |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
element_spec |
OutputSpec
|
The output spec of one element: its spec, |
axis_groups |
tuple of tuple of int or str
|
The axis sizes each level holds, in order, outermost level first. |
level_names |
tuple of str
|
One name per level, aligned with |
batch_shape |
tuple of int or str
|
The batch axes, flat: the concatenation of |
batch_size |
int
|
The total element count, |
Raises:
| Type | Description |
|---|---|
TypeError
|
If element is neither a |
ValueError
|
If no level is given, a level holds no axes, an axis size is negative or
is a name that is not a Python identifier, or a level name is empty or
contains |
Notes
A batch whose elements name no kind is specified all the same: an opaque element spec is as well formed here as any other, which is what lets a batch of opaque values carry a term spec of its own.
An axis size may be a symbolic dimension name instead of an integer, as
a NumericArraySpec shape entry may, so that a declaration can fix the number of
levels while deferring how many elements each holds — "returns a batch of
S draws" before S is known. The names share one scope with the
element's schema, so a batch of ("n",) over arrays of shape ("n",) is
square by declaration. Only the multiplicity must be concrete for a live
Batch, which holds elements at positions; an element's own schema may
stay polymorphic, since how many elements there are is a different question
from what one of them looks like.
A duplicate level name cannot be written in either form, and
Batch.with_level_names raises on a collision, since an operation that
mints a level takes the name to give it.
Examples:
>>> from probpipe import NumericArraySpec, OutputSpec
>>> BatchSpec(NumericArraySpec(()), sample=4).element_spec
OutputSpec(element=NumericArraySpec(shape=()))
>>> BatchSpec(NumericArraySpec(()), sample=4)
BatchSpec(NumericArraySpec(shape=()), sample=4)
>>> BatchSpec(OutputSpec(x=NumericArraySpec(())), sample=4)
BatchSpec(OutputSpec(x=NumericArraySpec(shape=())), sample=4)
Source code in probpipe/core/_batch.py
levels
property
¶
The levels as a read-only mapping from level name to its axis sizes, outermost first.
BatchSpec(element, spec.levels) rebuilds a spec with the same levels,
so another element type is declared over them.
batch_shape
property
¶
The batch axes, flat: the concatenation of axis_groups.
batch_size
property
¶
The total element count, prod(batch_shape).
Raises:
| Type | Description |
|---|---|
ValueError
|
If the multiplicity is polymorphic. A count is a number, and a
declaration that defers a size has none until it is bound — the same
reason a polymorphic |
free_dims
property
¶
The unbound dimensions of the element's schema and of the multiplicity.
One scope, as everywhere: a name shared between an axis size and the
element's schema is one dimension, so a batch declared as ("n",) of
arrays of shape ("n",) states that it is square.
free_axis_dims
property
¶
The unbound dimensions of the multiplicity alone.
What a live batch requires bound, since it holds elements at positions. An element's own schema may stay polymorphic: how many elements there are is a different question from what one of them looks like.
__replace__(**changes)
¶
This spec with the given fields replaced, for copy.replace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**changes
|
Any
|
New values of |
{}
|
Returns:
| Type | Description |
|---|---|
BatchSpec
|
The rebuilt spec, checked as a constructed one is. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a change names any other field. |
Source code in probpipe/core/_batch.py
__repr__()
¶
The constructor call: the element, then one keyword per level.
The element shows as its bare spec when the element spec is the raw
default for it, and as the element spec otherwise. A level of one axis
shows its size alone, as draw=4, and a level name that no keyword
spells puts the levels in one **{...} argument.
Source code in probpipe/core/_batch.py
is_valid(value)
¶
Whether value is a Batch whose own spec equals this one, element name aside.
The levels and the elements' specs are compared; the name an element
spec gives single values is not. An opaque type this spec leaves open
admits the type a batch inferred from its values, in the elements and in
any record field of them.
Anything that is not a Batch, or a Batch whose spec cannot be
read, does not satisfy the spec and returns False. Mirrors
is_valid.
Source code in probpipe/core/_batch.py
FunctionSpec(input_spec=None, output_spec=None)
dataclass
¶
Bases: TermSpec
A callable's optional inputs and output spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_spec
|
InputSpec or None
|
Named inputs. None leaves the input side unspecified. |
None
|
output_spec
|
OutputSpec or None
|
The returned term and its outputs. None leaves that side unspecified;
an output spec that names its output but leaves its type unspecified,
as |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If either side has the wrong spec type. |
Notes
is_valid admits any callable without executing it. Dimension binding
reads the input spec and output spec of each side when they are given,
sharing one dimension scope across both sides. A side left unspecified adds
no bindings. Incompatible input names,
output names or forms, kinds, or dimensions raise ValueError. Labels are
outside this spec; output names take part in matching the specs.
Examples:
A function's input spec and output spec bind a dimension that they share:
>>> from probpipe import FunctionSpec, InputSpec, NumericArraySpec, OutputSpec
>>> declared = FunctionSpec(
... InputSpec(x=NumericArraySpec(("n",))),
... OutputSpec(result=NumericArraySpec(("n",))),
... )
>>> actual = FunctionSpec(
... InputSpec(x=NumericArraySpec((3,))),
... OutputSpec(result=NumericArraySpec((3,))),
... )
>>> declared.bind_dims_from_spec(actual) == actual
True
>>> sorted(declared.free_dims)
['n']
Source code in probpipe/values/_function_base.py
free_dims
property
¶
Unbound dimensions across both sides, in one scope.
is_valid(value)
¶
__repr__()
¶
The declared sides, as the constructor takes them; an unspecified side is omitted.
Source code in probpipe/values/_function_base.py
DistributionSpec(event_spec)
dataclass
¶
Bases: TermSpec
The distribution kind's term spec: the output spec of one draw.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_spec
|
OutputSpec or RecordSpec
|
The output spec of one draw. A bare |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If event_spec is neither, since a bare spec of another kind has no output name to complete it with. |
ValueError
|
If event_spec leaves its type unspecified. |
Notes
is_valid accepts a Distribution whose own event spec unifies with
this one: the form and the output names agree, and then the outputs
unify in one scope. An unset dtype accepts any dtype and a set one
requires a same-kind cast, sizes agree with symbolic dimensions bound
consistently, and support is not compared.
bind_dims_from_value binds a symbolic event spec from a law's own, and
bind_dims_from_spec from another DistributionSpec, by that same rule.
Repeated symbols share one scope, and conflicting sizes raise ValueError.
Examples:
>>> from probpipe import DistributionSpec, OutputSpec, NumericArraySpec
>>> declared = DistributionSpec(OutputSpec(x=NumericArraySpec(("n",))))
>>> bound = declared.bind_dims_from_spec(DistributionSpec(OutputSpec(x=NumericArraySpec((3,)))))
>>> bound.event_spec.term_spec.shape
(3,)
Source code in probpipe/distributions/_distribution.py
probpipe.distributions.ConditionalDistributionSpec(given_spec, event_spec)
dataclass
¶
Bases: TermSpec
The conditional kind's term spec: the inputs and the event spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
given_spec
|
InputSpec, Mapping, RecordSpec, or OutputSpec
|
The named inputs a kernel conditions on, at least one. |
required |
event_spec
|
OutputSpec or RecordSpec
|
The output spec of one produced draw, as for |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If event_spec is neither an |
ValueError
|
If given_spec has no inputs, the event spec leaves its type unspecified, or an input shares a name with an output. |
Notes
is_valid accepts a ConditionalDistribution whose inputs have
the same names and specs that unify with these, and whose event spec
unifies with this one, both sides in one dimension scope.
Source code in probpipe/distributions/_conditional.py
free_dims
property
¶
The unbound dimensions of both sides, which share one scope.
__repr__()
¶
The inputs and the event spec, as the constructor takes them.
Source code in probpipe/distributions/_conditional.py
is_valid(value)
¶
Whether value is a ConditionalDistribution whose specs match these.
Source code in probpipe/distributions/_conditional.py
Input and output specs¶
An InputSpec reads another input spec, a mapping, a RecordSpec's top-level
fields, or an OutputSpec's outputs. Copying an input spec preserves its optional
inputs. Tuple shapes are shorthand for NumericArraySpec, in input declarations
and keyword output declarations alike:
from probpipe import InputSpec, OutputSpec, RecordSpec
inputs = InputSpec(mu=(), observations=(100,))
event = OutputSpec(RecordSpec(mu=(), sigma=()))
mu_input = InputSpec(event[["mu"]])
Pass a law's event_spec directly as given_spec when a kernel takes those
outputs as inputs. Use event_spec[["mu"]] to retain one output, or
event_spec.without("sigma") to remove an output. To pass a whole record as one
input, retain its named group with list selection. These declarations name
inputs; passing the law itself does not describe their types.
Input list selection retains declaration order and optional flags. Merging
input specs with left & right retains the first type of a shared input after
checking compatibility. A shared input is optional only when both sides mark it
optional. A Python parameter's default marks its declared input optional;
declaring an optional input for a parameter with no default is an error.
Record field order is part of a declaration. An existing record or record spec
in another order does not conform, including inside a nested record. At function
input and return boundaries, and when binding a kernel's conditioning values,
a raw mapping may arrive in any order: the body and returned value receive its
fields in declaration order. This leaves the caller's mapping unchanged.
Raw mappings supplied as density values are arranged against the law's event
spec before type inference, including nested records. Their insertion order
does not constrain the event layout. A constructed Record already has an
ordered declaration and must conform in that order.
InputSpec.without raises KeyError for a name it does not declare.
InputSpec(inputs=None, /, **inputs_by_name)
dataclass
¶
Bases: Mapping[str, TermSpec]
An immutable, flat mapping of input names to term specs.
An input is required or optional. A binding may omit an optional input, which
then takes the default of the function or conditional distribution that owns
it; with_optional marks inputs optional, and the optional inputs are
part of the spec, so they take part in equality and hashing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
InputSpec, Mapping, RecordSpec, or OutputSpec
|
Inputs in their source's order. A record spec supplies one input per top-level field, an output spec one per output, and another InputSpec preserves its optional flags. Other sources supply required inputs. |
None
|
**inputs_by_name
|
TermSpec or tuple
|
Alternatively, the inputs by keyword, including RecordSpec-valued inputs. A tuple of sizes is converted to a NumericArraySpec of that shape. No constructor keyword is reserved. |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the source is unsupported, positional and keyword forms are combined, an output spec has an unspecified type, or an input's type is not a hashable TermSpec or a tuple of sizes. An input's type cannot be None. |
ValueError
|
If an input name is not a non-keyword Python identifier, including path keys. |
Source code in probpipe/core/_specs.py
optional
property
¶
The inputs a binding may omit, which then take their defaults.
required
property
¶
The inputs a binding must supply, in order.
free_dims
property
¶
The shared dimension scope of all inputs.
is_concrete
property
¶
Whether all inputs have concrete dimensions.
__getitem__(names)
¶
An input's type, or the selected inputs in this spec's order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
str or sequence of str
|
One input name, or a list or tuple of input names. A one-element list still selects an InputSpec. |
required |
Returns:
| Type | Description |
|---|---|
TermSpec or InputSpec
|
The single input's type, or a spec retaining the selected inputs' order and optional flags. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a name is not an input. |
TypeError
|
If the selection is not a string or a list or tuple of strings. |
ValueError
|
If the list is empty, repeats a name, or contains overlapping paths. |
Notes
Interim implementation detail: paths into a record input are not read yet. Select its input name to retain that entire record.
Source code in probpipe/core/_specs.py
__contains__(name)
¶
get(name, default=None)
¶
The type of input name, or default when it is not an input name.
__and__(other)
¶
Merge inputs in order of first appearance, checking shared types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
InputSpec
|
Inputs to append or match to this spec's inputs. |
required |
Returns:
| Type | Description |
|---|---|
InputSpec
|
This spec's inputs followed by new inputs from other. A shared input is optional only when optional in both. Shared dimension bindings are applied throughout the result and not retained. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If other is not an InputSpec. Convert an output spec with InputSpec(output_spec) before merging it. |
ValueError
|
If shared types cannot describe one value, or a shared dimension would have two sizes. |
Notes
Interim implementation detail: a shared input keeps its first type, with dimension bindings applied, rather than the unified type.
Source code in probpipe/core/_specs.py
__repr__()
¶
Each input as a keyword, as the constructor takes it, then the optional inputs.
Source code in probpipe/core/_specs.py
with_optional(*names)
¶
The inputs with names optional, in addition to the inputs already optional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*names
|
str
|
The inputs to mark optional. |
()
|
Returns:
| Type | Description |
|---|---|
InputSpec
|
A new spec of the same inputs. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a name is not an input. |
Source code in probpipe/core/_specs.py
without(*names)
¶
The inputs other than names, each optional input staying optional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*names
|
str
|
Existing input names to remove. With none, all inputs are retained. |
()
|
Returns:
| Type | Description |
|---|---|
InputSpec
|
The retained inputs in declaration order, with their optional flags. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a name is not an input. |
TypeError
|
If a name is not a string. |
ValueError
|
If a name is malformed, repeated, or overlaps another name. |
Source code in probpipe/core/_specs.py
with_dim_sizes(**sizes)
¶
Return the inputs with supplied sizes substituted in their shared scope.
Source code in probpipe/core/_specs.py
with_dim_names(**names)
¶
Return the inputs with simultaneous symbolic-dimension renaming.
Source code in probpipe/core/_specs.py
bind_dims_from_value(value)
¶
Bind all inputs against named values in one shared dimension scope.
Raises ValueError for missing/extra inputs or conflicting sizes.
Source code in probpipe/core/_specs.py
bind_dims_from_spec(other)
¶
Bind against another input spec in one shared dimension scope.
Source code in probpipe/core/_specs.py
OutputSpec(*args, **term)
dataclass
¶
The outputs of a function's return value, of the values a distribution is over, or of a batch's elements.
An output is a name under which a value can be read and passed on to an
input of the same name. An OutputSpec holds a spec, term_spec, and its
outputs follow from it, in one of two forms:
- the positional form,
OutputSpec(RecordSpec(mu=(), sigma=())), has one output per top-level name of a record (muandsigma), or the outputs of a batch's elements. Over a distribution's or a conditional distribution's spec, as for a function that returns a distribution, it has no outputs; to pass the distribution on by name, put it in a record,OutputSpec(RecordSpec(params=d.spec)); - the keyword form,
OutputSpec(y=NumericArraySpec(())), names one output that holds the whole value.
An OutputSpec is indexed by path, as O["g/b"], and & merges two of
them. It is not a mapping and not iterable; outputs lists the outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
RecordSpec, DistributionSpec, ConditionalDistributionSpec, or BatchSpec
|
The positional form: the spec of the values, whose outputs are a record's top-level fields and groups, or the outputs of a batch's element, which is a record or a distribution; a distribution's or a conditional distribution's spec has none. |
()
|
**term
|
TermSpec, tuple, or None
|
The keyword form: one keyword, the output's name, over the spec of the
whole value. None means the type is not known yet; |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the positional form is not exactly one spec that has outputs, the forms are mixed, more than one keyword is given, or a record field lacks a spec. |
ValueError
|
If no spec is given, or an output name is empty or contains |
Examples:
>>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
>>> list(O.outputs)
['a', 'g']
>>> O["g/b"]
OutputSpec(b=NumericArraySpec(shape=()))
Notes
Only the form and the spec are stored; term_spec and outputs are
derived from them. An output of a record is a field or group of the value.
Source code in probpipe/core/_specs.py
term_spec
property
¶
The spec of the values described. None means the type is not known yet.
outputs
property
¶
Each output's name and spec, in order, as a read-only mapping.
is_concrete
property
¶
Whether the type is known and all its dimensions are concrete.
__repr__()
¶
The OutputSpec as the constructor takes it: one keyword, or one positional spec.
Source code in probpipe/core/_specs.py
__getitem__(paths)
¶
The OutputSpec at a path, or of a list of paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
str, or list or tuple of str
|
A path, such as |
required |
Returns:
| Type | Description |
|---|---|
OutputSpec
|
For one path, the OutputSpec of the value there: a single array or
opaque value has one output named by the path's last name, as
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a path of this OutputSpec's record. |
TypeError
|
If paths is neither a string nor a list or tuple of strings, or this OutputSpec has no paths to select, as over a single array or a distribution. |
ValueError
|
If a path is empty or has an empty name, or a list of paths is empty, names a path twice, or holds a path inside another. |
Notes
As an interim implementation detail, the name of the one output of the
keyword form gives this OutputSpec itself, as Normal("x", 0.0,
1.0)["x"] gives the distribution itself, until an accessor of an
output replaces both readings; a value with no paths has no path to
select.
Examples:
>>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
>>> O["g"]
OutputSpec(NumericRecordSpec(b=(), c=()))
>>> O[["g/b"]]
OutputSpec(NumericRecordSpec(g=NumericRecordSpec(b=())))
Source code in probpipe/core/_specs.py
__contains__(path)
¶
Whether path is a string and self[path] succeeds.
As [] does, it reads the name of the keyword form's one output as
an interim implementation detail.
Source code in probpipe/core/_specs.py
__iter__()
¶
Not supported: an OutputSpec is not a mapping; iterate over its outputs.
Raises:
| Type | Description |
|---|---|
TypeError
|
Always. |
Source code in probpipe/core/_specs.py
without(*paths)
¶
This OutputSpec without the values at some paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
str
|
The paths to remove, one per argument; a group left empty goes too. |
()
|
Returns:
| Type | Description |
|---|---|
OutputSpec
|
The rest, each value at its own path, in the same form. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a path of this OutputSpec's record. |
TypeError
|
If a path is not a string, or this OutputSpec has no paths to remove, as over a single array or a distribution. |
ValueError
|
If nothing would remain, or the paths name a path twice or a path inside another. |
Examples:
>>> O = OutputSpec(RecordSpec(a=(), g=RecordSpec(b=(), c=())))
>>> O.without("g/c")
OutputSpec(NumericRecordSpec(a=(), g=NumericRecordSpec(b=())))
Source code in probpipe/core/_specs.py
__and__(other)
¶
Merge two OutputSpecs: the outputs of both, this one's first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
OutputSpec
|
The outputs to add after this spec's. |
required |
Returns:
| Type | Description |
|---|---|
OutputSpec
|
The positional form over the record of both specs' outputs; the
output |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either spec's type is not known yet, or it is in the positional form over distributions, which have no outputs, or over batches, whose outputs are not read as one record yet. Wrap such values under a name to merge them. |
ValueError
|
If an output name is in both. |
Examples:
>>> OutputSpec(x=NumericArraySpec(())) & OutputSpec(RecordSpec(a=()))
OutputSpec(NumericRecordSpec(x=(), a=()))
Source code in probpipe/core/_specs.py
default(term_spec, *, output_name)
classmethod
¶
The OutputSpec ProbPipe uses for values of term_spec when none is given.
It is OutputSpec(term_spec) if term_spec is a RecordSpec, whose
fields and groups become the outputs, and
OutputSpec(**{output_name: term_spec}) otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
term_spec
|
TermSpec
|
The spec of the values. |
required |
output_name
|
str
|
The name of the one output when term_spec is not a |
required |
Returns:
| Type | Description |
|---|---|
OutputSpec
|
The positional form for a record, and the keyword form otherwise. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If term_spec is not a record and output_name is not a valid output name. |
Source code in probpipe/core/_specs.py
with_term_spec(term_spec)
¶
This OutputSpec with its spec completed from term_spec.
Where this OutputSpec's spec is None, which means the type is not known
yet, it becomes term_spec. Otherwise the declared spec must unify with
term_spec, and the result keeps the names and the form and stores their
unification: a numeric array keeps its declared dtype and support and
takes term_spec's where the declared spec leaves them unset, and a
declared dimension name binds to the size term_spec gives. A record
unifies field by field, and an opaque spec takes the known type and
meta. Any other kind takes term_spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
term_spec
|
TermSpec
|
The spec of the actual values. |
required |
Returns:
| Type | Description |
|---|---|
OutputSpec
|
The completed OutputSpec. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If this OutputSpec is in the positional form and term_spec is not a
spec of the same kind, such as a |
ValueError
|
If the declared spec does not unify with term_spec. |
Source code in probpipe/core/_specs.py
rename(renames=None, /, **keyword_renames)
¶
Rename or move nodes of this OutputSpec by their paths, old -> new.
A path starts with an output. In the positional form over a record, the
paths are the record's; in the keyword form, a path is the output's name
followed by a path within its value. Each key is the exact path of a node
and each target its new exact path, under the rule of
rename. The result
keeps the form. In the positional form a move may add or remove an
output. In the keyword form the output is renamed in place and the
fields of its value stay under it, so a field moves only within the
output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
renames
|
Mapping of str to str
|
The new path of each node, keyed by the node's path. |
None
|
**keyword_renames
|
str
|
The new path of each output, keyed by the output's name. |
{}
|
Returns:
| Type | Description |
|---|---|
OutputSpec
|
The renamed OutputSpec. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a key is not a path of this OutputSpec. |
TypeError
|
As |
ValueError
|
As |
Source code in probpipe/core/_specs.py
with_dim_sizes(**sizes)
¶
This OutputSpec with dimension names bound to sizes, keeping its form.
Source code in probpipe/core/_specs.py
with_dim_names(**names)
¶
This OutputSpec with dimension names renamed, keeping its form.
Source code in probpipe/core/_specs.py
Constraints¶
Constraint
¶
Describes the support of a distribution (the set of valid values).
check(value)
¶
Return a boolean array indicating which elements satisfy the constraint.
A support that is a subset of the reals contains a complex entry only where its imaginary part is zero and its real part is in the support.
Source code in probpipe/core/constraints.py
real = _Real()
module-attribute
¶
The support of all finite real numbers.
positive = _Positive()
module-attribute
¶
The support of the strictly positive reals, (0, inf).
non_negative = _NonNegative()
module-attribute
¶
The support of the non-negative reals, [0, inf).
non_negative_integer = _NonNegativeInteger()
module-attribute
¶
The support of the non-negative integers, {0, 1, 2, ...}.
boolean = _Boolean()
module-attribute
¶
The support of the binary values {0, 1}.
unit_interval = _UnitInterval()
module-attribute
¶
The support of the closed unit interval, [0, 1].
simplex = _Simplex()
module-attribute
¶
The probability simplex: non-negative vectors that sum to one along the last axis.
positive_definite = _PositiveDefinite()
module-attribute
¶
The support of the positive-definite matrices.
sphere = _Sphere()
module-attribute
¶
The unit sphere: vectors of unit Euclidean norm along the last axis.
interval(low, high)
¶
greater_than(lower_bound)
¶
integer_interval(low, high)
¶
The support of the integers in the closed interval [low, high].
Bijectors onto a support¶
bijector_for returns the canonical bijector from an unconstrained space onto a constraint's support.
register_bijector, on Registries for extensions, registers the bijector for a constraint.
bijector_for(constraint)
¶
The canonical bijector from ℝⁿ onto constraint's support.
The factory registered for constraint itself applies first, and then the one registered for the nearest type in its method-resolution order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constraint
|
Constraint
|
The support to map onto. |
required |
Returns:
| Type | Description |
|---|---|
Function
|
A map onto the support that claims |
Raises:
| Type | Description |
|---|---|
ResolutionError
|
If no factory is registered for constraint or its types, or the factory's map does not claim both capabilities. |
TypeError
|
If the factory returns neither a |
MathematicalDomainError
|
If constraint is a support onto which no smooth bijector exists, such as a discrete support or the unit sphere. |