AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Values and records¶
This page documents the value kinds, such as Record and NumericArray, their batches, and the linear operators.
The specs that declare these values are on Input and output specs, and the callable kind Function is on Functions.
Records¶
Record(fields, /, *, label=None, event_template=None, _validate_leaves=True)
¶
Bases: NamedTree[Any], TrackedTerm, Annotated
A single structured value with metadata.
A Record holds a single concrete value: an ordered, named collection
of fields. Every record stores its type as a RecordSpec that
encodes the structure of the value: the names, how the fields are stored,
and specs on the fields themselves. spec and event_template
return the same stored object. A record is immutable and its spec
is fixed at construction.
A named collection of values. A Record is a
NamedTree, so it inherits a
mapping/dictionary-like interface over the fields it stores: a field is accessed as
record["a"], and a nested field by its path, record["a/b/c"].
len(record) is the number of fields, and record.keys() /
record.values() / record.items() iterate the paths / field values / pairs.
The canonical field order is depth-first in insertion order. An empty record
requires an explicit root label. ::
r = Record(
{
"x": 1.5,
"y": Record(
{"a": 0.0, "b": 2.0},
label="y",
),
},
label="r",
)
r["x"] # 1.5
r["y/a"] # 0.0 — a nested leaf, by its path
len(r) # 3
list(r.keys()) # ['x', 'y/a', 'y/b']
Tree structure. A Record can equally be viewed as a tree, with the fields at
its leaves. The only allowed internal node is a nested Record, a
group; every other value is interpreted as a leaf. Names are unique within
each node, so every node has a unique /-path. The structure of the node
record[path] is described by the matching spec
record.event_template[path]. [] takes a path or a list of paths: one
path gives the node there, a field's value or a group's record, and a list or
a tuple of paths gives the record cut down to those nodes, each at its own
path and in this record's order, labeled by the paths. p in record is true
when record[p] gives a node, so it holds for a group, which keys()
does not list. children gives the one-level name -> child
view. ::
r["y"] # Record(a=0.0, b=2.0) — a group
r["y"]["a"] # 0.0, the same node as r["y/a"]
r["x", "y/b"] # Record {x, y: {b}}, labeled "(x, y/b)"
r[["y"]] # Record {y: {a, b}}: a list of one path keeps the name
"y" in r # True
dict(r.children) # {'x': 1.5, 'y': Record(a=0.0, b=2.0)}
Structure encoded by the event template. event_template always reflects
the structure of the stored value. Because a RecordSpec is itself a
NamedTree, its tree mirrors the record's exactly:
each nested Record corresponds to a nested RecordSpec, and each field value
corresponds to a value spec (an array to an NumericArraySpec, any non-array
to an OpaqueSpec, and so on). ::
r.event_template
# NumericRecordSpec(x=(), y=NumericRecordSpec(a=(), b=()))
r.event_template["y/a"] # NumericArraySpec(shape=()) — the spec for r["y/a"]
# A record's group and its template's group stay in lock-step:
r["y"].event_template == r.event_template["y"] # True
# Each field value maps to a value spec by type:
Record(
{"vec": jnp.zeros(3), "label": "fox"},
label="r",
).event_template
# RecordSpec(vec=(3,), label=OpaqueSpec(type=str)) — array -> NumericArraySpec
Metadata: identity and annotations. A record is a tracked term: it is
TrackedTerm, carrying a human-readable label
and, optionally, a provenance, the Provenance
describing how it was created, attached write-once via with_provenance. It is
also Annotated, so free-form annotations may
be attached after construction.
Construction and validation. A record is built from a flat mapping of key/field
pairs — either as keyword arguments or as a single positional mapping, but not both.
Mappings are never leaves: a mapping value denotes tree structure, so a plain
dict passed as a field value is materialised into a nested subtree — never
stored as a leaf — whether it appears as a keyword value or nested inside a
positional mapping. When every leaf is a numeric array (so
the carried template is a NumericRecordSpec), Record(...)
auto-promotes to NumericRecord, mirroring the
RecordSpec promotion; the numeric axis is re-derived whenever a
transform constructs a new record, so an edit that removes the last
non-numeric leaf promotes the result and one that introduces a
non-numeric leaf demotes it. An explicit non-numeric event_template
keeps the result a plain Record. ::
# All three build the same record:
Record(
{
"x": 1.5,
"y": Record(
{"a": 0.0, "b": 2.0},
label="y",
),
},
label="r",
)
Record(
{"x": 1.5, "y/a": 0.0, "y/b": 2.0},
label="r",
)
Record(
{"x": 1.5, "y": {"a": 0.0, "b": 2.0}},
label="r",
)
When an event_template is supplied it is validated against the value's
structure, and any mismatch in tree shape or field/spec kind raises
ValueError. When omitted, the template is inferred via
RecordSpec.infer_from; inference recovers the tree structure but
is lossy on the value specs (e.g. it cannot recover a FunctionSpec's
input / output structure). ::
Record(
{"a": 1.0},
event_template=RecordSpec(a=(), b=()),
label="r",
)
# ValueError: event_template fields ['a', 'b'] do not match record fields ['a'] ...
Equality and hashing. Two records are equal when they share a concrete class
(both Record, or both NumericRecord), have equal event_template\ s,
and are field-by-field equal. Because equality includes the template, whether an
identity transform round-trips to an equal record depends on how it treats
the template. A transform that threads the template through — replace
/ merge / without, or reconstruction via
Record.from_field_values — preserves it exactly and compares
equal. A transform that instead re-infers the template — map /
map_with_keys, which rebuild the result and re-infer its specs — compares
equal only when inference recovers the original template, for instance when
that template was itself inferred (the record was built without an explicit
event_template). Inference is lossy: RecordSpec.infer_from
cannot recover a NumericArraySpec's dtype / support, an
OpaqueSpec's meta, etc., so an identity map of a record carrying
a richer explicit template does not compare equal::
r.map(lambda x: x) == r # True only if r's template is inference-recoverable
Hashing is structural: a record's hash combines its class, its field names, and each field's shape and dtype (nested records hash recursively; an opaque leaf falls back to its type). It fingerprints the record's structure rather than its data, so records that share a structure fall in the same hash bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
Mapping
|
Field values in canonical first-appearance order. A mapping value becomes
a nested record. Slash-delimited keys declare nested paths. Fields named
|
required |
label
|
str
|
The root's display alias. Defaults to |
None
|
event_template
|
RecordSpec
|
The authoritative schema. Defaults to the schema inferred from the fields. A supplied schema is validated and its shared dimensions are bound jointly. |
None
|
_validate_leaves
|
bool
|
Whether to validate leaves against a supplied template. Internal numerical reconstruction skips this check. Numeric records still require numeric leaves. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the field paths conflict or a supplied |
TypeError
|
If fields is not a mapping; if it is a string and label is omitted, which is the earlier label-first form; if a field key is not a string; or if fields is empty and label is omitted, which leaves nothing to derive the label from. |
Notes
A Record is a registered JAX PyTree, but the tree from JAX's perspective
may differ from the tree from ProbPipe's perspective. ProbPipe only allows
nested Records to be internal nodes, while JAX also descends into
container leaves like tuples and lists (which Record views as single
opaque leaves). A dict is never a leaf — a mapping denotes tree
structure — so it does not arise as a container leaf here. This
implies that JAX sees a tree with finer structure, so that methods like
jax.tree_util.tree_flatten / tree_leaves / tree_map
(and jit / vmap / grad) descend into nested
Record\s and into container leaves like tuples and lists.
It is thus typically best practice to use the custom Record functionality
for traversing the fields. The above JAX functions will work, but users must
be aware that they will traverse the finer tree. The two notions of the tree
coincide when every field is an array (e.g. NumericRecord).
The PyTree registration's children are the field values and its static aux
data is the spec alone, so the declared type survives a tree_flatten /
tree_unflatten round-trip and two records that differ only in their
labels have equal treedefs and share a compilation. The label, the
expression, provenance, and annotations do not cross a
JAX transform boundary: a record rebuilt from its leaves is labeled
<no description> until a result boundary labels it, and
with_label relabels it otherwise. On a NumericRecord, the
flatten boundary is also where native leaves convert to jax.Array, so
a value that crosses a JAX transform comes back with bare-array leaves.
Source code in probpipe/core/record.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 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 | |
spec
property
¶
This record's own RecordSpec — the single stored source of its type.
Fixed at construction and always present. The schema is the kind spec
itself; event_template exposes the same object.
event_template
property
¶
The authoritative RecordSpec describing this value's structure.
Returns the same object as spec, fixed at construction and always
present. When a declaration was supplied (carried forward from the
producing generator) it describes that structure; otherwise one was
inferred from the field data at construction (via RecordSpec.infer_from).
Notes
Inference is a lossy fallback (it cannot recover a NumericArraySpec's
dtype / support, an OpaqueSpec's meta, or declarations not carried by an untracked value), so both round
trips out of this process carry the declaration rather than re-deriving
it: the spec rides in the JAX pytree aux data, and __reduce__
serializes it. A value reconstructed by tree_unflatten or by
pickle.loads carries this same structure.
raw
property
¶
The stored representation: the nested mapping of raw leaves.
A leaf is held in native form, so its raw value is the leaf itself, and a
tracked term held as a leaf, such as a law, gives its own raw. An
interior node gives the nested mapping of the raw leaves beneath it. A
node's stored form is read from the mapping, as record.raw["g"]["x"],
which also works inside a JAX trace. A field's view has a raw of its
own, record["g/x"].raw, which presents the leaf as the view's kind
does, so a Python scalar becomes an array, and inside a trace indexing
returns the traced leaf itself, which has no raw.
The leaves are resolved on the first read and kept, so a stored law is
detached once, and each read returns a new dict over them that the
caller may change. A record has a raw form only when every leaf has
one, so a leaf whose raw form raises, such as a field view with no
exact marginal, makes the read raise. A record holding a traced leaf
keeps nothing.
select(*paths, **mapping)
¶
The nodes at paths in a plain dict, keyed for splatting into a call.
A positional path is keyed by its last name, so select("a", "g/c")
gives {"a": self["a"], "c": self["g/c"]}, and a keyword names the
key, so select(x="g/c") gives {"x": self["g/c"]}. A path to a
group gives the group's record. The result is a value-only dict,
not a Record, and carries no schema.
Usage::
predict(**params.select("r", "K"), x=x_grid)
predict(**params.select(growth_rate="r"), x=x_grid)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
str
|
Paths to select, each keyed by its last name in the result. |
()
|
**mapping
|
str
|
Paths to select, each keyed by its keyword in the result. |
{}
|
Returns:
| Type | Description |
|---|---|
dict of str to Any
|
The node at each path, the positional paths first. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a path of this record. |
TypeError
|
If a path is not a string. |
ValueError
|
If a path is empty or has an empty name, or two entries would take
the same key, as |
Source code in probpipe/core/record.py
select_all()
¶
Return every top-level field as a dict, for splatting into a call.
Sugar for select over the one-level names (self.children). On the
batch and distribution subclasses, whose __getitem__ returns a
per-field view, the dict holds those views, so the result can be splatted
back into a Function field-by-field.
Source code in probpipe/core/record.py
without(*paths)
¶
Return a new Record without the fields and groups at paths.
The structural contract is NamedTree.without. Surviving fields
keep their order and their authoritative specs; an untouched child is
reused verbatim (class and metadata preserved), and a group a path
reaches into is edited recursively. Dropping every leaf under a child
prunes that child entirely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
str
|
One path per argument. |
()
|
Returns:
| Type | Description |
|---|---|
Record
|
The record without those nodes, under this record's label. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a path of this record. |
TypeError
|
If a path is not a string, such as a tuple of paths. |
ValueError
|
If a path is empty or has an empty name, the paths name a path twice or a path inside another, or every field would be removed. |
Source code in probpipe/core/record.py
__and__(other)
¶
Merge two records by top-level name: this record's fields and groups, then other's.
The merge is shallow, as NamedTree.__and__ states: a top-level
name present in both records raises, even when the two groups hold
different fields. Each child is reused as it is, with its class and
metadata, and both records' specs are carried into the merged
event_template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Record
|
The record whose fields and groups are added. |
required |
Returns:
| Type | Description |
|---|---|
Record
|
Both records' fields and groups side by side. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If other is not a record, through |
ValueError
|
If a top-level name is in both records. Merge the groups first. |
Examples:
Source code in probpipe/core/record.py
replace(_updates=None, /, **updates)
¶
Return a new Record with the values at the given paths replaced.
The structural contract is NamedTree.replace: every path must
already exist, and a partial path replaces a whole subtree. Untouched
fields keep their authoritative specs (untouched children are reused
verbatim — class and metadata preserved); a replaced field takes its
new value's inferred spec; a nested update edits the nested child
recursively. Overlapping update paths (one an ancestor of another)
raise ValueError.
Source code in probpipe/core/record.py
rename(renames=None, /, **keyword_renames)
¶
Return a Record with the given nodes renamed or moved, old -> new.
The structural contract is NamedTree.rename: each key
is the exact path of a node and each target its new exact path. The
authoritative event_template is renamed by the same rule, so the
subtree invariant holds on the result. The record keeps its label, since
with_label relabels the record itself, and the result carries no
provenance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
renames
|
Mapping of str to str
|
The new path of each node, keyed by the node's path. |
None
|
**keyword_renames
|
str
|
The new path of each top-level node, keyed by the node's name. |
{}
|
Returns:
| Type | Description |
|---|---|
Record
|
A record over the same leaves at their new paths. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a key is not the path of a node. |
TypeError
|
As |
ValueError
|
As |
Source code in probpipe/core/record.py
to_dict()
¶
Return a nested dict of stored values (leaves verbatim, no coercion).
Temporary: this is the same nested-tree export as to_nested_dict
(the canonical name). It is retained during the migration and scheduled
for removal; new code should call to_nested_dict. (The flat,
path-keyed view is the builtin dict(record).)
Source code in probpipe/core/record.py
to_numpy()
¶
Return a dict of numpy arrays (recursive for nested Record).
Each numeric leaf is converted via np.asarray. Non-numeric
leaves (strings, opaque objects) are returned as-is. Backend
metadata (xarray dims / coords, pandas index) is stripped by this
export — the record itself keeps its leaves in native form, so
read the fields directly when you need the original containers.
Source code in probpipe/core/record.py
to_numeric()
¶
Return this value as a NumericRecord, validating — not converting.
Every leaf must be numeric (a numeric scalar, a bare jax / numpy
array, or a native container such as an xarray / pandas
object). Leaves are stored in native form — nothing is coerced;
conversion to jax.Array happens lazily at the compute boundary.
Nested Record children recurse — every level becomes a
NumericRecord. On a value that is already a NumericRecord
this is the identity (returns self).
Returns:
| Type | Description |
|---|---|
NumericRecord
|
A new record with this record's label and leaves, whose spec is inferred from the leaves. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If any leaf is not numeric (e.g. strings, opaque Python objects). |
Source code in probpipe/core/record.py
from_fields(**fields)
classmethod
¶
Construct a record whose field names determine its label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**fields
|
Any
|
Field values, including fields named |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The record, promoted to its numeric kind when appropriate. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If no fields are given, since the label is derived from them. |
ValueError
|
If a field name contains |
Source code in probpipe/core/record.py
ensure(x, *, label=None)
classmethod
¶
Coerce x to a record, returning a record unchanged.
- a
Recordis returned as it is, and label is ignored; - a mapping becomes a record of its entries, and a nested mapping value becomes a nested record;
- any other value becomes a record of one field,
data, holding it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The value to coerce. |
required |
label
|
str
|
The label of a newly built record. A record built from a mapping is
labeled |
None
|
Returns:
| Type | Description |
|---|---|
Record
|
x itself when it is a record of this class; otherwise a new record,
promoted to |
Raises:
| Type | Description |
|---|---|
TypeError
|
If x is a value other than a mapping or a tracked term and label is omitted, or x is an empty mapping and label is omitted. |
ValueError
|
If the fields of a mapping x are invalid, as the constructor states. |
Source code in probpipe/core/record.py
from_dict(fields, *, label=None)
classmethod
¶
Construct a record from a dict of field values.
It is the same as Record(fields, label=label), and remains as the
dict-named spelling of that call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
dict
|
The field values, keyed by field name. |
required |
label
|
str or None
|
Keyword-only. The record's label; |
None
|
Returns:
| Type | Description |
|---|---|
Record
|
The record, promoted to |
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is omitted and fields is empty, or fields is a string, which is a label passed first in the earlier form. |
ValueError
|
If a field name or value is invalid, as the constructor states. |
Source code in probpipe/core/record.py
from_field_values(template, values, *, label=None)
classmethod
¶
Reconstruct a value from an ordered sequence of field values.
values supplies one object per field, in canonical order (the order
of the template's keys); the names and tree shape
come from template, which the result carries as its
authoritative event_template (nothing is inferred), so
the round-trip is faithful:
Record.from_field_values(r.event_template, r.values(), label=r.label) == r.
The export side is just list(record.values()). The result's class
follows the template's numericness — a NumericRecordSpec
builds a NumericRecord via the auto-promotion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
RecordSpec
|
The authoritative schema supplying names, nesting, and order. |
required |
values
|
iterable
|
One field value per template key, in canonical order. |
required |
label
|
str or None
|
Keyword-only. The reconstructed record's label; |
None
|
Returns:
| Type | Description |
|---|---|
Record
|
The reconstructed value (a |
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is omitted and template has no fields, or template is a string, which is a label passed first in the earlier form. |
ValueError
|
If the number of values is not the number of fields
( |
Source code in probpipe/core/record.py
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 | |
__repr__()
¶
The label, then the field paths in canonical order, read from the schema.
A numeric record shows its values below them.
__eq__(other)
¶
Two records are equal iff they have equal structure and equal data.
Concretely, equality requires (1) the same concrete type, (2) equal
event_template (so two values with structurally distinct schemas
— e.g. differing support on a numeric leaf — are unequal even with
identical bytes), and (3) field-by-field equal values. A numeric leaf
is compared on its native values (materialised through the
array-backend registry — the same basis fingerprint uses, so
equality and the content fingerprint agree) and on its
native-container metadata (an xarray leaf's coords / dims / attrs,
a pandas leaf's index / columns): two leaves with equal values but
different coords are unequal, because that metadata is observable
content. NaN positions compare equal (equal_nan), so a record
with a NaN leaf equals an independent copy of itself. Nested
records compare recursively; opaque leaves compare with ==.
Whether two records with equal data compare equal therefore turns on
their templates. Built from equal data without an explicit template,
both infer the same template and compare equal; but a record given a
richer explicit template compares equal to a re-inferred rebuild of
itself (e.g. via map) only when inference recovers that template,
since RecordSpec.infer_from is lossy (it cannot recover a
NumericArraySpec's dtype / support, etc.).
__hash__ is a coarser, structural hash (shape only, never the
values or metadata), so equal records always hash equal while records
that differ only in values or coords legitimately collide.
Source code in probpipe/core/record.py
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 | |
NumericRecord(fields, /, *, label=None, event_template=None, _validate_leaves=True)
¶
A Record whose fields are all numeric, stored in native form.
A NumericRecord is the numeric specialization of Record. It
holds the same named, ordered, possibly-nested collection of fields, but
constrains every field to be numeric. It inherits the full
Record interface — the leaf-keyed mapping, the tree navigation,
the metadata (label, provenance), and the
equality and hashing rules — and adds the array-only features described
below.
The numeric-leaf invariant, and native storage. Every field must be numeric — a
numeric array or container from any supported backend (jax.numpy, numpy,
xarray.DataArray, a pandas object with numeric dtypes, or any type
registered via register_array_backend), or a numeric Python scalar
(int, float, complex, or bool); interior nodes are
themselves NumericRecord instances. Construction validates without converting: an
array-like leaf is stored verbatim in its native form, reading only its
container metadata (shape / dtype), so a lazy or disk-backed value is
not materialised. A bare Python scalar — which carries no metadata — is
normalised to a 0-d jax.Array. Any non-numeric leaf raises
TypeError at construction, naming the offending field.
Lazy conversion at the compute boundary. Navigation returns native leaves
verbatim: record["x"], children, and at_path
never convert. Conversion to jax.Array happens at the compute boundary — the JAX
pytree flatten that jit / vmap / grad traverse,
to_vector, and the single-field scalar shim — through a per-leaf
cache. Concrete conversions are memoised per record instance; traced
conversions stay within their transform. A JAX transform
returns a record with bare jax.Array leaves (unflatten
cannot rebuild native containers); structural transforms
(without / merge / replace
/ rename) and pickling reuse the native leaves
verbatim, so native types survive them.
Aliasing and mutation. Native leaves are stored by reference, exactly as a
plain Record stores opaque leaves, and construction marks a NumPy
array leaf read-only in place, so a write through the caller's handle or
through raw raises ValueError. A pandas or xarray
container carries no such flag, so mutating it in place after construction
changes the record. Once that leaf has crossed a compute boundary,
navigation and compute can disagree: navigation reflects the mutation, but
compute reuses the jax.Array snapshot cached at the first concrete
conversion. Records assume their containers are not externally mutated
mid-pipeline; no defensive copies are made.
Equality, hashing, and lazy leaves. __eq__ and content
fingerprints compare converted values (and native-container metadata such as coords
/ index), so computing them on a record with lazy / disk-backed leaves forces
materialisation on demand. __hash__ is a coarser structural hash
over shape and dtype only — it reads container metadata, never the values, so
hashing a lazy leaf does not materialise it (records differing only in
values or coords hash equal, a legal collision).
The flat vector form. Because every leaf is numeric, the record implements
Numeric, and the whole value can be flattened into a
single dense 1-D array. to_vector converts and ravels the leaves,
in canonical order, into a vector of length vector_size;
from_vector rebuilds the record from such a vector (with bare
jax.Array leaves). Note that this is different from
list(record.values()), which returns the ordered list of native
fields and is supported by any Record.
Truth depends on the number of top-level fields, as for any record: an empty record is false and every nonempty record is true.
Single-field records as scalars. A NumericRecord with exactly one field
behaves like a thin wrapper around that field's value: float(r), int(r),
np.asarray(r), jnp.asarray(r), and the r.shape /
r.dtype / r.ndim attributes all forward to the sole leaf (only the value
coercions materialise it). A record with more than one field, or
whose single child is a nested record — an interior node, not a field —
raises TypeError from these conversions, since unwrapping one field of
several would be ambiguous; access a specific field explicitly in that
case. The array conversions override the ones Numeric
supplies, which present to_vector. The override is an interim
implementation detail until a record no longer presents a single field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
Mapping
|
Field values in canonical first-appearance order. A mapping value becomes
a nested record. Slash-delimited keys declare nested paths. Fields named
|
required |
label
|
str
|
The root's display alias. Defaults to |
None
|
event_template
|
NumericRecordSpec
|
The authoritative schema. Defaults to the schema inferred from the fields. A supplied schema is validated and its shared dimensions are bound jointly. |
None
|
_validate_leaves
|
bool
|
Whether to validate leaves against a supplied template. Internal numerical reconstruction skips this check. Numeric records still require numeric leaves. |
True
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If any leaf is not a numeric array or container, a numeric scalar, or a
nested |
ValueError
|
If the field paths conflict or a supplied |
Notes
Constructing NumericRecord(fields, label=label), constructing
Record(fields, label=label) from all-numeric fields (which auto-promotes),
and calling to_numeric() follow the same validation path and produce
identical results; to_numeric() on an existing NumericRecord is
the identity.
The compute boundary presents a plain PyTree of arrays: the JAX pytree
children are the converted leaves, so jit / vmap / grad see
exactly the ProbPipe structure. As on Record, the PyTree aux
carries the (spec, label) pair, so the declared type
and the label survive a flatten/unflatten round-trip;
provenance, annotations, and the native container types
do not cross a JAX transform boundary.
Source code in probpipe/core/_numeric_record.py
vector_size
property
¶
Length of this record's 1-D vector (to_vector / from_vector).
The total number of scalar elements across all numeric leaves — the
length of to_vector's output. Computed from container
metadata at construction; no values are materialised.
dtype
property
¶
The sole leaf's dtype, or None when it has no single dtype.
A registered backend reports the leaf's dtype (None for a
heterogeneous container such as a mixed-column frame); a bare
array-like forwards its own .dtype. A leaf that exposes no single
dtype yields None rather than a stand-in.
to_vector()
¶
Serialize to the dense 1-D vector of shape (vector_size,).
The numeric 1-D serialization: the record's numeric leaves, visited in
canonical leaf order (keys —
insertion order, depth-first into nested records), each converted to
jax.Array at the compute boundary, raveled, and concatenated into
one dense vector. Concrete leaf conversions are memoised. The inverse is
from_vector.
This is distinct from list(record.values()), which keeps each leaf
whole and native (any type); to_vector ravels and concatenates the
numeric leaves into a single dense vector.
Source code in probpipe/core/_numeric_record.py
from_vector(spec, vec, *, label=None)
classmethod
¶
Reconstruct a single record from its dense 1-D vector.
The value-level inverse of to_vector: splits vec into the
spec's per-field blocks, reshapes each to its NumericArraySpec shape
in canonical leaf order, and returns a NumericRecord carrying
spec as its authoritative schema under label.
The reconstructed leaves are bare jax.Array\ s — a flat vector
carries no native container to restore.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NumericRecordSpec
|
The flat layout supplying field names, shapes, and order. Every leaf must be a NumericArraySpec. |
required |
vec
|
Array
|
A vector of shape |
required |
label
|
str or None
|
Keyword-only. The reconstructed record's label; |
None
|
Returns:
| Type | Description |
|---|---|
NumericRecord
|
The reconstructed record, with |
Raises:
| Type | Description |
|---|---|
TypeError
|
If spec contains a non-array leaf; if vec carries
leading batch axes — batched reconstruction is
the batch type's concern; use |
ValueError
|
If the vector length does not equal |
Source code in probpipe/core/_numeric_record.py
to_numeric()
¶
__repr__()
¶
The class and the label, then one line for each field with its path and its value.
A nested path reads population/mu. NumPy's printing formats each
value, so np.set_printoptions sets the precision and shortens a large
array with ..., and a shortened value ends with its shape. Only the
entries shown are read from the device. Inside a JAX trace, where the
values are tracers, and for a record with no fields, the repr is the
summary of the label and the field paths.
A record of summaries displays as a table under its label instead. Its
top-level fields are records over the same paths, with the same shape
at each path, and at least one of them records how it was computed, as
the term an operation returns does. The table has one row for each
path, or for each element of an array path, as y[0], and one column
for each top-level field, and its lines are indented by two spaces, as a
record's lines are. The line below the table states how each column
was computed: exact, Monte Carlo with the number of draws, or
approximate.
Source code in probpipe/core/_numeric_record.py
__str__()
¶
The lines of the repr's values alone, one for each field with its path and its value.
A record that displays as a table gives the table without its label and
the line below it. Inside a JAX trace, and for a record with no fields,
str() is the summary of the label and the field paths.
Source code in probpipe/core/_numeric_record.py
__bool__()
¶
Whether this record holds any field, at any depth, whatever its values.
A record whose only top-level name is an empty group holds no field, so it is false, as its length of 0 says.
Source code in probpipe/core/_numeric_record.py
Numeric arrays¶
NumericArray(value, /, *, label, spec=None, provenance=None)
¶
Bases: TrackedTerm, Annotated, Numeric
One numeric array value, with identity.
The tracked class of the numeric-array kind, as Record is
of the record kind: what an operation returns when its declared kind is a
NumericArraySpec. It holds a single array and carries no
batch axes, so shape is the event shape; multiplicity lives in
NumericArrayBatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
array - like
|
The array this term holds, stored verbatim in its native form: a bare array,
an |
required |
label
|
str
|
The value's required semantic name. A value carries no fields to describe it, so the label is what says which one it is; a class-name default would label every array in a pipeline alike. |
required |
spec
|
NumericArraySpec
|
What this value satisfies. Derived from the array's shape and dtype when omitted, with an unconstrained support. |
None
|
provenance
|
Provenance
|
How this value was produced. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If spec is not a |
ValueError
|
If value's shape or dtype does not satisfy spec. |
Notes
Construction validates native arrays and NumPy scalars against metadata
alone, deferring JAX conversion to as_jax. NumPy scalars retain their
original precision in raw and np.asarray(value). JAX conversion
follows its x64 configuration and can round or overflow; float(value)
also goes through as_jax.
It carries the full array surface: arithmetic, comparison, and the
conversion hooks. With one value and no fields, arr + 1 has a single
meaning, which is what lets Record stay a container.
It implements Numeric: its vector is the array raveled in
row-major order, and its conversion hooks present the array itself rather
than that vector, so NumPy and JAX functions see its shape and return bare
arrays.
An operator returns a NumericArray holding the stored value's result,
labeled by the expression in evaluation order, such as draw + 1, with its
tracked operands as the provenance's parents. A term presents as its raw
representation inside a JAX trace, so there an operator returns the bare
result. Indexing and iteration return the stored value's entries and rows.
As a JAX pytree it flattens to its array, with its spec as the static
data. The label and the expression do not cross a transform, so two values
that differ only in their labels have equal treedefs and share a
compilation, and a value rebuilt from its leaves is labeled
<no description> until a result boundary labels it.
Examples:
>>> import jax.numpy as jnp
>>> value = NumericArray(
... jnp.arange(3.0),
... label="draw",
... )
>>> value.shape
(3,)
>>> value + 1
NumericArray('draw + 1', shape=(3,), dtype=float32)
[1. 2. 3.]
Source code in probpipe/core/_numeric_array.py
raw
property
¶
The stored array, in the form it was given. Untracked.
spec
property
¶
This value's own declaration.
shape
property
¶
The event shape, read from the value's metadata. No batch axes.
dtype
property
¶
The stored value's dtype, or None when it has no single one.
The value's rather than the declaration's, as for a single-field
NumericRecord: a caller sizing a buffer or branching on the dtype is
asking about the data. The two can differ, since is_valid admits a
same-kind cast; spec carries the declaration.
vector_size
property
¶
Length of this array's 1-D vector, the number of its elements.
as_jax()
¶
The value as a jax.Array — the single conversion point.
A value already stored as one passes through, tracers included; a native container converts through its registered backend. Concrete conversions are memoised; traced conversions stay within their transform.
Conversion follows JAX's x64 configuration, so a stored float64 can become float32 and round or overflow when x64 is disabled. Enable x64 before the first conversion when float64 is required; an existing concrete cache is reused even if that configuration later changes.
Source code in probpipe/core/_numeric_array.py
to_vector()
¶
Serialize to the dense 1-D vector of shape (vector_size,), in row-major order.
The value converts to jax.Array at the compute boundary, as
as_jax does. The inverse is from_vector.
Source code in probpipe/core/_numeric_array.py
from_vector(spec, vec, *, label)
classmethod
¶
Reconstruct a single array from its dense 1-D vector.
The value-level inverse of to_vector: reshapes vec to the shape
spec declares, casts it to the declared dtype when there is one, and
returns a NumericArray carrying spec under label. The rebuilt
value is a bare jax.Array, since a flat vector carries no native
container to restore.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NumericArraySpec
|
The declaration supplying the shape and dtype, with every dimension bound. |
required |
vec
|
Array
|
A vector of shape |
required |
label
|
str
|
Keyword-only and required, with no default, since a raw array's data cannot identify the value. |
required |
Returns:
| Type | Description |
|---|---|
NumericArray
|
The reconstructed array, whose |
Raises:
| Type | Description |
|---|---|
TypeError
|
If vec is not one-dimensional, since a batch of vectors belongs to
|
ValueError
|
If spec has unbound dimensions, or the vector's length is not
|
Source code in probpipe/core/_numeric_array.py
__str__()
¶
The stored value's entries as NumPy prints them, as print shows the array.
Inside a JAX trace, where the value is a tracer, str() is the
repr's summary.
Source code in probpipe/core/_numeric_array.py
__format__(format_spec)
¶
The stored value formatted by format_spec, as f"{x:.2f}" formats a scalar.
__repr__()
¶
A summary of the label, the shape, the dtype, and any support, then the entries below it.
Each line of the entries is indented by two spaces, as a record's lines
are. NumPy's printing formats the entries, so np.set_printoptions sets
their precision and shortens a large array with ..., and only the
entries shown are read from the device. Inside a JAX trace, where the
value is a tracer, the repr is the summary alone.
Source code in probpipe/core/_numeric_array.py
Numeric
¶
Bases: ABC
The flat-vector interface of the numeric kinds.
NumericArray and NumericRecord implement it.
A numeric value lays itself out as one flat vector in canonical order.
to_vector returns that vector, vector_size is its length,
and from_vector rebuilds a value from one. The base supplies the
coordinate protocols, which present the vector to NumPy and JAX, so their
functions return bare arrays. A batch form is not Numeric, since its
elements are the numeric values.
Notes
NumericArray restates the coordinate protocols to present
its array itself, whose row-major order is its vector's.
NumericRecord restates them to present its sole field, an
interim implementation detail until a record no longer presents a single
field.
vector_size
abstractmethod
property
¶
The length of this value's flat vector.
to_vector()
abstractmethod
¶
from_vector(spec, vec, *, label)
abstractmethod
classmethod
¶
Rebuild the value that spec declares from its flat vector vec.
It inverts to_vector. Every numeric kind takes label, so a
caller that holds only a Numeric class passes it. A kind may also
derive a default, as NumericRecord.from_vector
<probpipe.NumericRecord.from_vector> derives one from the record's
top-level fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NumericSpec
|
The declaration of the value, which supplies its layout. |
required |
vec
|
Any
|
The flat vector, of length |
required |
label
|
str
|
Keyword-only. The label of the rebuilt value. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
The value whose |
Source code in probpipe/core/_numeric.py
Opaque values¶
Opaque(value, /, *, label, spec=None, provenance=None)
¶
Bases: TrackedTerm, Annotated
One value of no exposed structure, with identity.
The tracked class of the opaque kind, as Record is of the
record kind: what an operation returns when its declared kind is an
OpaqueSpec. Its batch form is
OpaqueBatch.
Its interface is raw plus the identity every tracked term carries.
What the value affords is its own type's, once it is out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value this term holds, stored as given. Any non-mapping value; the value layer reads a mapping as a subtree. A NumPy array is marked read-only in place. |
required |
label
|
str
|
The required semantic description, passed by keyword: an opaque value has no fields or callable name from which to derive one. |
required |
spec
|
OpaqueSpec
|
What this value satisfies, carrying any opaque |
None
|
provenance
|
Provenance
|
How this value was produced. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If spec is not an |
Examples:
>>> fitted = Opaque(
... object(),
... label="sklearn_model",
... )
>>> fitted.label
'sklearn_model'
Source code in probpipe/core/_opaque.py
Batches¶
Batch
¶
Bases: TrackedTerm, ABC
A tracked nd collection of elements of a common type.
The batch axes are grouped into named levels, and indexing them returns a
view — an element once the selection reaches one, a sub-batch otherwise —
whose label records what it selected. Index by position with [], by level
name with at_levels, and, where the elements have fields, by field
name with [] as well; len and iter walk the leading axis.
A concrete subclass supplies the element storage, calling _init_batch
from its constructor; this class stores the batch's BatchSpec and the
identity TrackedTerm provides, and nothing else.
Attributes:
| Name | Type | Description |
|---|---|---|
spec |
BatchSpec
|
This batch's own specification, at the family kind. The single stored source of its type: everything below is a view on it. |
element_spec |
OutputSpec
|
The output spec of one element: its spec, |
batch_shape |
tuple of int
|
The batch axes, the flat concatenation of |
batch_size |
int
|
The total element count, |
axis_groups |
tuple of tuple of int
|
|
level_names |
tuple of str
|
One name per level, aligned with |
Notes
batch_shape and batch_size are named rather than reusing numpy's
shape / size because a bare name would ambiguously cover both the
batch axes and the content of one element.
A batch is immutable, by Immutable:
assignment and deletion raise, and pickle / copy restore its state
around that guard.
spec
property
¶
This batch's own specification, at the family kind.
element_spec
property
¶
The output spec of one element: its spec, element_spec.term_spec, and its outputs.
A view on spec. A batch built from bare values takes the raw
default, which names single arrays or opaque values "element".
batch_shape
property
¶
The batch axes, flat: the concatenation of axis_groups.
batch_size
property
¶
The total element count, prod(batch_shape).
axis_groups
property
¶
batch_shape tiled into levels, outermost level first.
level_names
property
¶
One name per level, aligned with axis_groups.
with_level_names(mapping=None, /, **kwargs)
¶
Rename levels old -> new; shapes and elements are unchanged.
Accepts a positional mapping, keyword pairs, or both. Every name given must be a level of this batch, and the result must still name each level once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping of str to str
|
Renames as |
None
|
**kwargs
|
str
|
Renames as |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A shallow copy over the same axes and elements, specified over the new level names, preserving its own label. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a name to rename is not a level of this batch. |
ValueError
|
If a level is renamed twice with different names, or a new name is
empty, contains |
TypeError
|
If a new name is not a string. |
Notes
The level counterpart of rename, which renames the fields
within an element. The two namespaces are independent: renaming a level
never touches a field name, or the reverse.
Source code in probpipe/core/_batch.py
__repr__()
¶
The public class, the label, the levels, and the elements' structure.
A numeric batch shows its values below them.
__len__()
¶
__iter__()
¶
__getitem__(paths_or_positions)
¶
Index the batch axes by position, or every element by path.
By position, a single indexer addresses the leading axis and a tuple
the leading axes in order, as batch[i, j] does for an array. Each
indexer is an integer, anything with __index__ such as a NumPy or JAX
integer scalar, or a slice; an integer drops its axis and a slice keeps
it, a whole axis being written :. The result is an element once
every axis is dropped and a sub-batch view otherwise, exactly as for
at_levels, which is the by-name counterpart over levels.
By path, batch["x"] addresses the node at the path x of every
element, and a list or a tuple of paths, as batch["a", "g/c"], the
elements cut down to those nodes. A tuple is read as a list of paths; a
nested path is written with /. A batch whose elements are records
answers; a batch whose elements are arrays or opaque values has no
paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths_or_positions
|
int, slice, str, list, or tuple
|
An integer, a slice, or a tuple of them addresses the batch axes; a string is read as one path, and a list or a tuple of strings as a list of paths. |
required |
Returns:
| Type | Description |
|---|---|
E or Self or Any
|
An element or a sub-batch view for a position; the batch of the elements' nodes for paths. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If more indexers are given than there are batch axes, or an integer is out of range for its axis. |
KeyError
|
If the elements are records and a path is not one of their paths. |
TypeError
|
If paths_or_positions is neither a position nor paths, such as |
ValueError
|
If a slice has a step of zero, a path is empty or has an empty name,
or a list of paths is empty, as |
Notes
The two readings never collide, an axis having no name and a path no
position, which is what lets one operator serve both. The axis side is
stated once here for every batch; the path side is left to
_at_paths. None is not a position: it spells a whole axis in
at_levels alone, where a keyword cannot take a : literal.
Source code in probpipe/core/_batch.py
__contains__(path)
¶
Whether path is a str and a path of the elements; an element is never tested.
at_levels(**levels)
¶
Index by named level, returning an element or a sub-batch view.
Each keyword names a level of this batch and gives it an indexer: an
integer, a slice, None, or a tuple of those addressing the level's axes
in order. An integer drops its axis; a slice or None keeps it, None
standing for the whole axis as : does. A shorter tuple fills the
level's leading axes and leaves the rest whole, so a scalar draw=i on a
two-axis draw level means draw=(i, None). A level not named is kept
whole, and a level whose axes are all dropped is removed, yielding the
inner batch or element just as positional indexing does.
A level name that is no Python identifier is passed in a mapping, as
at_levels(**{"my level": 0}). The receiver is positional-only, so every
level name is addressable as a keyword — including one that happens to
spell a parameter of this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**levels
|
int, slice, None, or tuple
|
One indexer per named level, keyed by the level's name. |
{}
|
Returns:
| Type | Description |
|---|---|
E or Self
|
The element the selection reaches, or a sub-batch view over the levels that remain. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a keyword is not a level of this batch. |
ValueError
|
If a level is given more indexers than it has axes, or a slice has a step of zero. |
IndexError
|
If an integer is out of range for its axis. |
TypeError
|
If an indexer is not an integer, a slice, |
Notes
The by-name counterpart of positional [], and the level analogue of
NamedTree.at_path: a path addresses a position in a tree and returns a
leaf or a subtree, while named level indexers address positions here and
return an element or a sub-batch. None spells a whole axis in this form
alone, a keyword being unable to take a : literal; positional []
writes : and refuses None.
Source code in probpipe/core/_batch.py
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 | |
RecordBatch(fields, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)
¶
A batch of records sharing one RecordSpec, stored as columns.
RecordBatch(...) returns a NumericRecordBatch when every
column is a numeric array and element is omitted or a
NumericRecordSpec, as Record(...) returns a
NumericRecord when every field is numeric. A subclass
constructs its own class.
As a JAX pytree it flattens to its columns, with its spec as the static
data. The label and the expression do not cross a transform, so two
batches that differ only in their labels have equal treedefs and share a
compilation, and a batch rebuilt from its leaves is labeled
<no description> until a result boundary labels it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
Mapping of str to array
|
The field columns, keyed by leaf path ( |
required |
level_names
|
str or sequence of str
|
One name per level, outermost first; a single string names a single
level. There is no default, for the reason
|
required |
label
|
str
|
The batch's label. Defaults to |
None
|
element
|
RecordSpec
|
The schema and kind spec every element satisfies. Defaults to the spec
the columns imply, as a |
None
|
axes_per_level
|
int or sequence of int
|
How many axes each level holds, outermost first (a single int is one level's count); they must account for every batch axis. Defaults to one axis per level, which requires as many names as there are batch axes. The sizes are read off the elements rather than restated here — they are already fixed by the data, so the only thing left to say is where one level ends and the next begins. |
None
|
provenance
|
Provenance
|
How this batch was produced. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
spec |
BatchSpec
|
This batch's own type, at the family kind over its elements'. |
element_spec |
OutputSpec
|
The output spec of one element, whose outputs are the record's top-level
fields and groups — a view on |
event_template |
RecordSpec
|
The structure of one element, |
Raises:
| Type | Description |
|---|---|
TypeError
|
If element is not a |
ValueError
|
If fields is empty; if its keys are not exactly the fields of element; if a column's trailing axes are not the event shape its field declares; if two columns disagree on the batch axes; if a field declares a symbolic dimension, which gives its event shape no size to split by; if a column leaves no batch axis; or if axes_per_level does not account for every batch axis, or gives a count that is not one per level. |
TypeError
|
If level_names is not a str or a sequence of str, or axes_per_level is
not an int or a sequence of ints; a generator, a set, |
ValueError
|
If an axes_per_level count is less than 1, or a level name is empty or
contains |
Notes
Construction requires at least one field, not at least one element: a
zero-sized column is a batch of nothing, which is what a declared aggregate
over no rows is, and batch[0:0] selects the same thing. What cannot be
admitted is an empty field mapping, which fixes neither the fields nor a shape
to read the batch axes from.
An object column is copied and frozen, so a caller keeping a handle on what they passed cannot afterwards write a value the batch's spec refuses. Only the pointer array is copied, so the elements stay shared. An array column is stored as given: a JAX array is already immutable, and a NumPy array is marked read-only in place, as a record marks its leaves.
Reading one element materializes it from the columns, which costs one gather per field, so iterating a batch is proportional to elements × fields. Reading a column costs nothing of the sort — prefer it where a whole field will do.
Examples:
>>> import jax.numpy as jnp
>>> from probpipe import RecordSpec
>>> batch = RecordBatch(
... {"x": jnp.zeros((3, 2))},
... "draw",
... element=RecordSpec(x=(2,)),
... label="draws",
... )
>>> batch.batch_shape
(3,)
>>> batch["x"].shape
(3, 2)
>>> batch[0].label
'draws[draw=0]'
Source code in probpipe/core/_record_batch.py
event_template
property
¶
The structure of one element, element_spec.term_spec.
raw
property
¶
The storage view: the nested mapping of the raw columns.
Each column is its field's raw batch form, the stacked array for an
array field and the frozen object array for any other field. A node's
columns are read from the mapping, as batch.raw["g"]["x"].
The nesting is built on the first read and kept, and each read returns
a new dict over the columns that the caller may change. A batch
holding a traced column keeps nothing.
select(*paths, **mapping)
¶
Batch views of the nodes at paths, keyed for splatting into a call.
The batch counterpart of select, keyed the same
way: a positional path is keyed by its last name, so select("a",
"g/c") has the keys "a" and "c", and a keyword names the key,
so select(x="g/c") keys the view of g/c under "x". A path to
a field gives a one-field view, and a path to a group the batch of the
group's records. Each entry is a RecordBatch view rather than a bare
array, so splatting the result into a Function call carries the
level names an operation aligns operands by.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
str
|
Paths to select, each keyed by its last name in the result. |
()
|
**mapping
|
str
|
Paths to select, each keyed by its keyword in the result. |
{}
|
Returns:
| Type | Description |
|---|---|
dict of str to RecordBatch
|
One view per path, at this batch's levels, the positional paths first. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a path of the elements. |
TypeError
|
If a path is not a string. |
ValueError
|
If a path is empty or has an empty name, or two entries would take
the same key, as |
Source code in probpipe/core/_record_batch.py
select_all()
¶
Every top-level part as a batch view, keyed by its own name.
Keyed by top-level name rather than by leaf path, as
select_all is, so the result splats into a call:
a name binds to a parameter where a /-path could not. A top-level
name that is an interior node gives the sub-batch beneath it, so the parts
cover the batch between them.
Source code in probpipe/core/_record_batch.py
rename(renames=None, /, **keyword_renames)
¶
Rename or move nodes old -> new within every element.
The element counterpart of with_level_names,
which renames the levels: the two namespaces are independent, and
renaming one leaves the other unchanged. Each key is the exact path of a
node of the elements and each target its new exact path, under the rule
of rename. Each
column is stored under its field's new key, so no stored value changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
renames
|
Mapping of str to str
|
The new path of each node of the elements, keyed by the node's path. |
None
|
**keyword_renames
|
str
|
The new path of each top-level node of the elements, keyed by the node's name. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A batch over the same values and levels, its elements' nodes renamed. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a key is not the path of a node of the elements. |
TypeError
|
As |
ValueError
|
As |
Source code in probpipe/core/_record_batch.py
without(*paths)
¶
Drop the fields or subtrees at paths from every element.
Each path is a key, dropping one field, or a partial path, dropping the subtree beneath it. The surviving fields keep their order and their specs, and the batch axes are unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
str
|
The keys and partial paths to drop. |
()
|
Returns:
| Type | Description |
|---|---|
Self
|
A batch over the surviving columns, at the same levels. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a field or an interior node of the elements. |
ValueError
|
If every field would be dropped — a batch of records with no fields is not a value. |
Source code in probpipe/core/_record_batch.py
replace(_updates=None, /, **updates)
¶
Replace the values at the given paths, across the whole batch.
Each replacement is that field's values for every element, shaped
(*batch_shape, *event_shape) — the same form the field is read back
in, not one element's value. Every path must already exist: this edits,
it does not add. An untouched field keeps its spec; a replaced one takes
the spec its new values imply.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_updates
|
Mapping of str to Any
|
The replacements keyed by field key, which may address a field at any depth. Passing it together with keyword updates raises. |
None
|
**updates
|
Any
|
The replacements keyed by the name of a top-level field. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A batch over the edited columns, at the same levels. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a field of the elements. |
ValueError
|
If no updates are given, or a replacement does not carry the batch axes. |
Source code in probpipe/core/_record_batch.py
__and__(other)
¶
Merge this batch's elements with other's by top-level name, element by element.
Both batches must span the same axes under the same level names, since
the result's elements pair up one for one. The merge is shallow, as
Record.__and__ states: a top-level name, a field or a group, in
both batches raises. Each side keeps its own fields' specs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
RecordBatch
|
The batch whose fields are added. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A batch over both sets of columns, with this batch's fields first. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If other is not a batch of records. |
ValueError
|
If the two disagree on their levels or axes, or a top-level name is in both. |
Source code in probpipe/core/_record_batch.py
map(f, /, *args, **kwargs)
¶
Apply f to every field's values, keeping the structure.
What a batch presents at each field is that field's values across the batch, so that is what f receives — one call per field, vectorized, rather than one per element. A function that preserves the batch axes therefore yields a batch of the same shape; each field takes the spec its result implies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
callable
|
Called as |
required |
*args
|
Any
|
Further positional arguments of f, the same for every field. |
()
|
**kwargs
|
Any
|
Further keyword arguments of f, the same for every field. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A batch over the results, at the same levels. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a result does not carry the batch axes. |
Source code in probpipe/core/_record_batch.py
map_with_keys(f, /, *args, **kwargs)
¶
map, with each field's leaf path passed as the first argument.
Source code in probpipe/core/_record_batch.py
stack(records, *, level_name, element=None, label=None)
classmethod
¶
Stack records into a batch with one level of (len(records),).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list of Record
|
The elements, all conforming to one template. At least one. |
required |
level_name
|
str
|
Names the level the stacking mints. Required, since the operation doing the stacking is what knows what the axis means. |
required |
element
|
RecordSpec
|
The spec every element satisfies. Taken from the first record when
omitted, which is exact whenever the records were built against a
shared declaration, with each opaque field typed by what its values
share, as an |
None
|
label
|
str
|
The batch's label. Taken from the first record when omitted — a batch of
|
None
|
Returns:
| Type | Description |
|---|---|
RecordBatch
|
The batch, with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If records is empty, or a record's fields are not exactly the spec's, naming the record's position and what differs. |
Notes
Nested templates stack like any other: a column is keyed by leaf path, so a nested field is one column and nesting costs the stacking nothing.
Source code in probpipe/core/_record_batch.py
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 | |
__eq__(other)
¶
Whether other is the same class, equally specified, with equal columns.
Equality is structural over the stored columns, compared field by field.
A batch is unhashable for the reason an array-carrying container usually
is — see __hash__.
Source code in probpipe/core/_record_batch.py
NumericRecordBatch(fields, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)
¶
Bases: RecordBatch
A RecordBatch whose every column is a numeric array.
The all-numeric specialization, carrying a NumericRecordSpec: a bare
pytree of arrays whose leading axes are the batch_shape, so its columns
are the leaves jit / vmap / grad traverse. The batch itself is
rebuilt only under a transform that keeps every batch axis or removes all of
them; see the module docstring. It adds the batched flat layout,
to_vector and from_vector.
Construction is that of RecordBatch, narrowed: element, given
or inferred from the columns, must describe an all-numeric element, and every
column must carry a numeric dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
Mapping of str to array
|
The numeric columns, keyed by leaf path or given as a nested mapping, each
shaped |
required |
level_names
|
str or sequence of str
|
One name per level, outermost first; a single string names a single level. |
required |
label
|
str
|
The batch's label. Defaults to |
None
|
element
|
RecordSpec
|
The all-numeric schema every element satisfies. Defaults to the spec the columns imply. |
None
|
axes_per_level
|
int or sequence of int
|
How many axes each level holds, outermost first (a single int is one level's count). Defaults to one axis per level. |
None
|
provenance
|
Provenance
|
How this batch was produced. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If element does not describe an all-numeric element, or a column is not a numeric array. |
TypeError
|
If level_names is not a str or a sequence of str, or axes_per_level is
not an int or a sequence of ints; a generator, a set, |
ValueError
|
If an axes_per_level count is less than 1, or a level name is empty or
contains |
Source code in probpipe/core/_numeric_record_batch.py
event_template
property
¶
The numeric structure of one element, element_spec.term_spec.
shape
property
¶
The sole field's full shape, (*batch_shape, *event_shape).
dtype
property
¶
The sole field's dtype.
ndim
property
¶
The rank of the sole field's values, batch axes included.
__repr__()
¶
The class, the label, and the levels, then one line for each field with its values.
Each line gives a field's path and its stored column, batch axes
leading, as NumPy prints it, so np.set_printoptions sets the
precision and shortens a large column with ..., and a shortened
column ends with its shape. Only the entries shown are read from the
device. Inside a JAX trace, where the columns are tracers, the repr is
the summary of the label, the levels, and the field paths.
A batch of records of summaries, whose provenance describes how each
column of each element was computed, as the batch summarize returns
for a batch of laws does, shows one table for each element instead, as
a record's repr states. Each table is titled by its element's levels, as
law=0, each title is indented by two spaces and each table by four,
and the elements are shortened to edgeitems at each end when their
rows number more than NumPy's threshold. The line that states how
the columns were computed follows each table, or follows the last when
every element's line is the same.
Source code in probpipe/core/_numeric_record_batch.py
__str__()
¶
The lines of the repr's values or tables alone, or the summary inside a JAX trace.
Source code in probpipe/core/_numeric_record_batch.py
__array__(dtype=None, copy=None)
¶
The sole field's values as a numpy array.
Source code in probpipe/core/_numeric_record_batch.py
__jax_array__()
¶
to_vector()
¶
Every element's flat vector, stacked.
Returns:
| Type | Description |
|---|---|
Array
|
Shape |
Notes
Distinct from reading the columns, which keeps each field whole and its event axes intact. The batch axes are left as they are: a multi-level batch keeps its levels as the leading axes of the result, so the flat dimension is always the last one and the levels read outermost-first.
Source code in probpipe/core/_numeric_record_batch.py
from_vector(spec, vec, *, level_names, axes_per_level=None, label=None)
classmethod
¶
Rebuild a batch from its elements' flat vectors, inverting to_vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NumericRecordSpec
|
The flat layout: field names, event shapes, and canonical order. Every leaf must be a NumericArraySpec. |
required |
vec
|
Array
|
Shape |
required |
level_names
|
str or sequence of str
|
One name per level of the reconstructed batch, outermost first; a
single string names a single level. Required for the reason
|
required |
axes_per_level
|
int or sequence of int
|
How many axes each level holds, as for the constructor. Omitted, a
single name takes all of vec's batch axes as one level and several
names take one axis each. The first is why a draw of several axes
reconstructs without naming each: a |
None
|
label
|
str or None
|
Keyword-only. The reconstructed batch's label; |
None
|
Returns:
| Type | Description |
|---|---|
NumericRecordBatch
|
The batch, satisfying |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the spec contains a non-array leaf; if vec has no batch
axis — reconstruct a single value with |
ValueError
|
If the trailing axis is not |
Examples:
A two-level batch round-trips when both levels are named:
>>> import jax.numpy as jnp
>>> from probpipe import RecordSpec
>>> spec = RecordSpec(x=(2,))
>>> batch = NumericRecordBatch(
... {"x": jnp.zeros((4, 5, 2))},
... ("chain", "draw"),
... element=spec,
... label="post",
... )
>>> rebuilt = NumericRecordBatch.from_vector(
... spec, batch.to_vector(), level_names=("chain", "draw"), label="post")
>>> rebuilt.batch_shape
(4, 5)
Source code in probpipe/core/_numeric_record_batch.py
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 | |
NumericArrayBatch(values, /, level_names, *, label, element=None, axes_per_level=None, provenance=None)
¶
Bases: Batch[NumericArray]
A batch of numeric arrays sharing one NumericArraySpec.
Storage is a single array with the batch axes leading — the split
RecordBatch uses, with one column instead of many. This
is where a draw level lives for an array-valued law. As a JAX pytree it
flattens to that array with its spec as the static data, so the label and
the expression do not cross a transform, and a batch rebuilt from its
leaves is labeled <no description> until a result boundary labels it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
array - like
|
One array holding every element, shaped |
required |
level_names
|
str or sequence of str
|
One name per level, outermost first; a single string names one level. |
required |
label
|
str
|
The batch's label, required, as an unnamed array's and an
|
required |
element
|
NumericArraySpec
|
The spec every element satisfies. Its |
None
|
axes_per_level
|
int or sequence of int
|
How many axes each level holds, outermost first (a single int is one level's count); they must account for every batch axis. Defaults to one axis per level, which requires as many names as there are batch axes. The sizes are read off the elements rather than restated here — they are already fixed by the data, so the only thing left to say is where one level ends and the next begins. |
None
|
provenance
|
Provenance
|
How this batch was produced. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If element is not a |
TypeError
|
Also if the stored array's dtype is one the declared element does not admit — a cross-kind conversion — or if the store reports no single dtype while the element declares one, which leaves the claim unsubstantiated. |
ValueError
|
If values has fewer axes than the event shape it must end with, which would leave no batch axis; if its trailing axes are not that event shape; if a declared dimension is symbolic, which gives the event shape no size to split by; if values has fewer axes than the levels hold, when the elements' spec is inferred; or if axes_per_level does not account for every batch axis, or gives a count that is not one per level. |
TypeError
|
If level_names is not a str or a sequence of str, or axes_per_level is
not an int or a sequence of ints; a generator, a set, |
ValueError
|
If an axes_per_level count is less than 1, or a level name is empty or
contains |
Notes
Selection yields the element kind, as it does for every batch:
batch[i] is a NumericArray. It materializes, so each element
takes the derived label and inherits this batch's lineage.
Source code in probpipe/core/_numeric_array_batch.py
raw
property
¶
The storage view: the stored array with the batch axes leading, in native form. Untracked.
shape
property
¶
The store's full shape, (*batch_shape, *event_shape).
dtype
property
¶
The store's dtype — the value's, as a NumericArray's is.
ndim
property
¶
The rank of the store, batch axes included.
__repr__()
¶
The summary of the label, the levels, and the elements' spec, then the stored entries.
Each line of the entries is indented by two spaces, as a record's lines
are. NumPy's printing formats the stored array, batch axes leading, so
np.set_printoptions sets the precision and shortens a large batch
with ..., and only the entries shown are read from the device.
Inside a JAX trace, where the store is a tracer, the repr is the summary
alone.
Source code in probpipe/core/_numeric_array_batch.py
__str__()
¶
The stored entries alone, as the repr shows them, or the summary inside a JAX trace.
as_jax()
¶
The store as a jax.Array — the single conversion point.
A store already held as one passes through, tracers included; a native container converts through its registered backend. Concrete conversions are memoised; traced conversions stay within their transform.
Source code in probpipe/core/_numeric_array_batch.py
OpaqueBatch(elements, /, level_names, *, label, element=None, axes_per_level=None, provenance=None)
¶
Bases: _ObjectBatch[Any]
A batch of opaque objects sharing one OpaqueSpec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elements
|
ndarray or iterable
|
The objects, as an object array of any shape or a flat iterable. |
required |
level_names
|
str or sequence of str
|
One name per level, outermost first. |
required |
label
|
str
|
The batch's label. Required, as it is for every batch: a batch is a value a caller holds, and a label derived from its class says nothing about what it holds. |
required |
element
|
OpaqueSpec
|
The spec every element satisfies. Defaults to the |
None
|
axes_per_level
|
int or sequence of int
|
How many axes each level holds, outermost first (a single int is one level's count); they must account for every batch axis. Defaults to one axis per level, which requires as many names as there are batch axes. The sizes are read off the elements rather than restated here — they are already fixed by the data, so the only thing left to say is where one level ends and the next begins. |
None
|
provenance
|
Provenance
|
How this batch was produced. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If element is not an |
ValueError
|
If |
TypeError
|
If level_names is not a str or a sequence of str, or axes_per_level is
not an int or a sequence of ints; a generator, a set, |
ValueError
|
If an axes_per_level count is less than 1, or a level name is empty or
contains |
Notes
An opaque value exposes no structure, so there is nothing to stack it into and the collection is a batch. An element may be any value except a mapping, which the value layer reads as a subtree rather than a leaf.
This is the case a batch's own spec exists for: an OpaqueSpec names no
ProbPipe kind, yet the batch is specified all the same, at the family kind
over it.
This batch stores its elements, and batch[i] is a view of the
stored object: an Opaque holding it under the label
derived from the position, or, for a stored tracked term, a copy of that
term under the derived label that shares its representation. Its provenance
records the batch and the stored term. A sub-batch is a view and takes a
derived label as any view does.
Examples:
>>> batch = OpaqueBatch(
... ["north", "south"],
... "site",
... label="labels",
... )
>>> batch.batch_shape
(2,)
>>> batch[0].raw
'north'
>>> batch[0].label
'labels[site=0]'
Source code in probpipe/core/_opaque_batch.py
Designs¶
Design(fields, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)
¶
Bases: RecordBatch
A batch of records that carries its per-field marginals.
A Design is not meant to be instantiated directly — concrete
subclasses (FullFactorialDesign) assemble the underlying
rows in __init__ and stash the originating marginals for
introspection.
Two equivalent ways to drive a sweep through a @function::
@function
def fit(p): ...
result = fit(p=design) # one row per call
@function
def fit(r, K): ...
result = fit(**design.select_all()) # zip across sibling views
select_all() returns one view per field; the views carry this Design's
own design level, and the sweep layer zips arguments that share a level
name (so the two shapes above produce identical outputs). For raw columns
(no sweep — just JAX broadcasting), index with design["r"].
Attributes:
| Name | Type | Description |
|---|---|---|
marginals |
Mapping[str, Any]
|
The per-field marginals this design was built from, in construction (insertion) order. Kept for introspection; read-only. |
Source code in probpipe/core/_record_batch.py
marginals
property
¶
Per-field marginals this design was built from.
FullFactorialDesign(**marginals)
¶
Bases: Design
Cartesian product over all marginals — one row per combination.
Each marginal is a Python sequence (list, tuple, numpy / jax
array). Numeric marginals become jnp.ndarray columns and
categorical / string marginals become numpy.ndarray(dtype=object)
columns. Row order is row-major over the marginals in insertion
order — i.e., the last-listed marginal varies fastest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**marginals
|
Sequence
|
Candidate values for each field. Must pass at least one marginal; each must be non-empty. |
{}
|
Examples:
Cartesian grid of two numeric fields:
>>> ff = FullFactorialDesign(r=[1.5, 1.8], K=[60.0, 80.0])
>>> ff.batch_shape
(4,)
>>> tuple(ff.event_template.keys())
('r', 'K')
Mixed numeric / categorical marginals are supported — columns fall
out as object-dtype arrays for the categorical fields:
Source code in probpipe/record/design.py
Weights¶
Weights(*, n=None, weights=None, log_weights=None)
¶
Normalized probability weights over n items.
Weights stores log-unnormalized weights internally for numerical
stability and provides lazy-cached access to normalized weights and
log-weights.
It implements the JAX array protocol (__jax_array__), so a
Weights object can be passed directly to any JAX operation that
expects an array — it will automatically convert to its normalized
weight vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of items. When provided alone (without weights or log_weights), creates uniform weights. When provided alongside an array, validates that the array length matches. |
None
|
weights
|
ArrayLike, Weights, or None
|
Non-negative weights. |
None
|
log_weights
|
ArrayLike, Weights, or None
|
Log-unnormalized weights. Preferred when weights span many
orders of magnitude (e.g. importance sampling). |
None
|
Examples:
Create from raw weights or log-weights:
>>> w = Weights(weights=jnp.array([1.0, 2.0, 1.0]))
>>> w = Weights(log_weights=jnp.array([-1.0, 0.0, -1.0]))
Create uniform weights:
Use as a JAX array — the normalized weights, so a sum is one:
That is what lets a Weights be passed anywhere a weight array is
expected, jax.random.choice(..., p=w) included, and used directly in
an array expression::
jnp.einsum("n,n...->...", w, vals) # weighted sum
w * values # element-wise product
Access different representations explicitly when needed::
w.normalized # Array, shape (n,) — probabilities summing to 1
w.log_normalized # Array — log-probabilities (always an array)
w.log_unnormalized # Array | None — raw stored log-weights (None if uniform)
w.is_uniform # bool — True when all items are equally weighted
Compute weighted statistics directly::
w.mean(values) # weighted mean along leading axis
w.variance(values) # weighted variance
w.covariance(values) # weighted covariance matrix
w.choice(key, shape=(10,)) # draw 10 weighted random indices
Passing to distribution constructors — a distribution constructor
that accepts weights also accepts a pre-built Weights object,
which is used as-is (no re-validation), so log-weights reach it as one::
w = Weights(log_weights=log_w)
EmpiricalDistribution(samples, weights=w, output_name="x")
JAX compatibility — Weights is registered as a JAX pytree
whose single leaf is the normalized weight array, so it works
transparently inside jax.jit, jax.vmap, jnp.sum,
jnp.einsum, and other JAX operations.
Notes
Zero weights and -inf in log-space. When a weight array
contains zeros (e.g. [0.0, 1.0, 0.0]), the internal
log-representation stores -inf for those entries. All
Weights operations handle this correctly:
normalizedproduces0.0for those items (via softmax).log_normalizedcontains-infentries (mathematically correct:log(0) = -inf).effective_sample_sizeis unaffected (logsumexphandles-infinputs).choicenever selects zero-weight items.
Code that consumes log_normalized directly should be aware
that -inf values may be present.
Source code in probpipe/_weights.py
n
property
¶
Number of items.
is_uniform
property
¶
True when all items are equally weighted.
normalized
property
¶
Normalized weights, shape (n,).
Cached after the first access outside a trace. A value computed while tracing belongs to that trace, so it is returned without being cached.
log_normalized
property
¶
Normalized log-weights, shape (n,).
Returns -log(n) for uniform weights, matching the behavior
of normalized which always returns an array.
log_unnormalized
property
¶
Raw log-unnormalized weights as stored. None when uniform.
effective_sample_size
property
¶
Kish's effective sample size (ESS).
.. math::
n_{\mathrm{eff}} = \frac{1}{\sum_i w_i^2}
where :math:w_i are the normalized weights. For uniform
weights this equals n exactly.
Computed in log-space for numerical stability:
.. math::
n_{\mathrm{eff}}
= \exp\!\bigl(-\log \sum_i \exp(2 \log w_i)\bigr)
= \exp\!\bigl(-\mathrm{logsumexp}(2\,\log\mathbf{w})\bigr)
Returns:
| Type | Description |
|---|---|
Array
|
Scalar effective sample size ( |
shape
property
¶
Shape of the weight vector: (n,).
dtype
property
¶
Data type of the underlying log-weights array.
For uniform weights, returns JAX's current default float dtype.
uniform(n)
staticmethod
¶
Create uniform weights over n items.
Equivalent to Weights(n=n) but avoids keyword overhead in
hot internal paths.
Source code in probpipe/_weights.py
__jax_array__()
¶
Return normalized weights as a JAX array.
This allows Weights to be used directly in JAX operations
(jnp.sum(w), jnp.einsum(..., w, ...), w * arr, etc.).
mean(values)
¶
variance(values, mean=None)
¶
Compute weighted variance over the leading axis.
covariance(values, mean=None)
¶
Compute weighted covariance matrix over the leading axis.
choice(key, *, shape=())
¶
Draw weighted random indices from 0..n-1, of shape shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKey
|
JAX PRNG key. |
required |
shape
|
int or sequence of int
|
The shape of the index array. A single int is one axis, so
|
()
|
Returns:
| Type | Description |
|---|---|
Array
|
Integer index array of shape shape. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If shape is not an int or a sequence of ints, or a size is a |
ValueError
|
If a size is negative. |
Source code in probpipe/_weights.py
subsample(indices)
¶
Return a new Weights for a subset, re-normalized.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Array
|
Integer indices selecting a subset of items. |
required |
Returns:
| Type | Description |
|---|---|
Weights
|
New |
Source code in probpipe/_weights.py
tree_flatten()
¶
Flatten for JAX pytree.
The single leaf is the normalized weight array so that JAX
operations (jnp.sum, jnp.einsum, etc.) receive a plain
array when unpacking the pytree.
Source code in probpipe/_weights.py
tree_unflatten(aux, children)
classmethod
¶
Unflatten from JAX pytree.
Source code in probpipe/_weights.py
Named trees¶
NamedTree
¶
The named, ordered tree addressed by path — the shared collection substrate.
A NamedTree is a named, ordered collection of fields stored in a
nested, tree-like structure: a field is one named leaf, and the leaf value
is nameless on its own — the name the tree gives it makes it a field. A
path is a str of /-joined names from the top of the tree down
to a node, which is a field or a group, a node that is itself a
tree. A child of a node is an entry directly under it, and the
canonical order is the depth-first walk visiting children in insertion
order. Sibling names are distinct, so every path identifies at most one
node; distinct groups may reuse a name (a/c and b/c).
keys(), values(), items(), iteration, and len range over
the fields, keyed by path in canonical order. [] takes a path or a
list of paths:
- one path, a
str, gives the node there: a field's object, or the group's tree, sox["a"]["b/c"] == x["a/b/c"]; - a list or a tuple of paths gives a tree of the same family cut down to those nodes, each at its own path and in this tree's canonical order, whatever order the paths are given in.
p in x is true when p is a str and x[p] gives a node, so
it holds for a group, which keys() does not list. children is
the one-level view of the storage, and at_path reaches the node at
a path given as separate segments, so x.children["a"].children["b"] is
the node that x.at_path("a", "b") and x["a/b"] address.
A child is an interior node if and only if it is an instance of the
family's own node class (the hook _node_type); every other value
is a leaf, validated against the family's declared _leaf_type at
construction. The static counterpart of that leaf type is the class type
parameter L — RecordSpec
binds TermSpec, Record
binds Any — which the leaf-trafficking accessors ([],
values, items, map) carry through to typed
consumers. Those accessors return each leaf as the family presents it
(the hook _present), which is the stored leaf unless the family
overrides the hook. Mappings are never leaves: a mapping value denotes tree
structure (see _check_leaf).
Navigation yields views into the same storage; the structure-preserving
transforms (map, replace, __and__, without,
rename) return a tree of the same family, rebuilt through
_rebuild_class.
This substrate provides no constructor logic; each family's constructor
owns storage (the _tree attribute) and validation policy.
fields
property
¶
Top-level field names, in insertion order — tuple(self.children).
Temporary, retained during the migration to the collection vocabulary;
new code should use children (one-level mapping) or keys
(leaf keys). It is scheduled for removal once that vocabulary is carried
onto the distribution layer, and should not be relied on in new code.
children
property
¶
Read-only one-level view of this node — local_name -> child.
Each value is an immediate child: a field object (leaf) or a subtree (a
nested collection of the same class). Insertion-ordered. This is the
labelled top-level view; the top-level names are tuple(obj.children).
Unlike the leaf-keyed field view, children.values() includes
subtrees.
is_multi_field
property
¶
Whether this tree holds more than one field.
Counts reachable fields recursively (descending into nested
subtrees), not top-level children — a single top-level child that
nests several fields is multi-field. Equivalent to len(self) > 1.
keys()
¶
The field keys (/-paths to the leaves), in canonical order.
Returns a reusable (materialised) tuple, matching the dict-like contract; iteration over the collection yields the same keys.
Source code in probpipe/core/named_tree.py
values()
¶
The field objects (one per leaf), in canonical order (materialised).
items()
¶
(key, field_object) pairs, in canonical order (materialised).
__getitem__(paths)
¶
The node at a path, or this tree cut down to the nodes at a list of paths.
A tuple is read as a list of paths; a nested path is written with /, so
x["g/c"] is the node c inside the group g, while
x["g", "c"] is the tree cut down to the top-level nodes g and
c.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
str, or list or tuple of str
|
One path, which gives the node there, or a list of paths, which gives a tree of the same family holding each of those nodes at its own path, in this tree's canonical order. |
required |
Returns:
| Type | Description |
|---|---|
L or Self
|
A field's object, a group's tree, or the cut-down tree. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a path of this tree. |
TypeError
|
If paths is neither a string nor a list or tuple of strings. |
ValueError
|
If a path is empty or has an empty name, or a list of paths is empty, names a path twice, or holds a path inside another. |
Source code in probpipe/core/named_tree.py
__contains__(path)
¶
Whether path is a str and a path of this tree, of a field or of a group.
Source code in probpipe/core/named_tree.py
at_path(*segments)
¶
The node at the path that segments spell: a field's object, or a group's tree.
Each segment is a name or a path, and the segments are joined with
/, so these are equivalent::
obj.at_path("physics/mass")
obj.at_path("physics", "mass")
obj["physics/mass"]
obj[path] is the recommended form; at_path reads the same node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*segments
|
str
|
The path's segments, one per argument. |
()
|
Returns:
| Type | Description |
|---|---|
L or Self
|
The field's object, as the family presents it, or the group's tree. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the path is not a path of this tree. |
TypeError
|
If a segment is not a string, such as a tuple of segments. |
ValueError
|
If no segment is given, or the path has an empty name. |
Source code in probpipe/core/named_tree.py
is_field(path)
¶
Whether path is the path of a field of this tree, rather than of a group or of nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
One path. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether a field is at path. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If path is not a string. |
ValueError
|
If path is empty or has an empty name. |
Source code in probpipe/core/named_tree.py
to_nested_dict()
¶
Return a nested dict mirroring the storage tree.
Each interior node becomes a nested dict; each leaf maps to its
field object. This is the tree-shaped export, distinct from the flat
dict(obj) view that is keyed by full path.
Source code in probpipe/core/named_tree.py
map(f, /, *args, **kwargs)
¶
Apply f to every field object, returning a same-shape collection.
Returns a new collection of the same structure (identical names and
nesting) whose fields are f's outputs, rebuilt through the class's
constructor via _rebuild_class — for the value types this is the
same class; a base RecordSpec may auto-promote to (or demote
from) NumericRecordSpec when the mapped specs change
numericness. f is
called as f(field_object, *args, **kwargs) for each field in canonical
order. Any extra args / kwargs are forwarded to f unchanged and are
constant across fields (not varied per field).
The structure is preserved exactly. f must return a leaf object, not an
instance of the node type (the class returned by _node_type); such
a return would introduce nesting and raises ValueError naming the
field. Each output is placed back through the subclass's own construction,
so whatever normalisation that constructor applies to a leaf applies here
too (see the concrete class's docstring).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
callable
|
The function applied to each field object. |
required |
*args
|
Any
|
Further positional arguments of f. |
()
|
**kwargs
|
Any
|
Further keyword arguments of f. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The collection of the outputs of f. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If f returns a node-type instance at any field. |
Source code in probpipe/core/named_tree.py
map_with_keys(f, /, *args, **kwargs)
¶
Like map, but f also receives each field's key (path).
f is called as f(key, field_object, *args, **kwargs), where key is
the field's full /-path. Everything else — structure preservation,
the node-type-return guard, per-class result handling — matches map.
Source code in probpipe/core/named_tree.py
without(*paths)
¶
Return a new collection with the fields and groups at paths removed.
Each path names a field, which is dropped, or a group, which is dropped
with every node below it. Surviving fields keep their order and their
specs, so a list of paths and without partition the fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*paths
|
str
|
One path per argument. |
()
|
Returns:
| Type | Description |
|---|---|
Self
|
The collection without those nodes. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a path is not a path of this tree. |
TypeError
|
If a path is not a string, such as a tuple of paths. |
ValueError
|
If a path is empty or has an empty name, the paths name a path twice or a path inside another, or every field would be removed. |
Source code in probpipe/core/named_tree.py
__and__(other)
¶
Merge two trees by top-level name: this tree's fields and groups, then other's.
The merge is shallow: a top-level name, a field or a group, present in both trees raises, even when the two groups hold different fields. To merge two groups of one name, merge the groups first and put the result under the name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
NamedTree
|
The tree whose fields and groups are added. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
Both trees' fields and groups side by side. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If other is not a tree of this family, through |
ValueError
|
If a top-level name is in both trees. |
Examples:
>>> from probpipe import RecordSpec
>>> (RecordSpec(a=(3,)) & (RecordSpec(g=RecordSpec(b=()))))
NumericRecordSpec(a=(3,), g=NumericRecordSpec(b=()))
Source code in probpipe/core/named_tree.py
replace(_updates=None, /, **updates)
¶
Return a new collection with the objects at the given paths replaced.
Updates are given as a path-keyed positional mapping
(r.replace({"physics/mass": m})) or flat keywords (r.replace(obs=y)),
not both. Every path must already exist (KeyError otherwise — replace
edits, it does not add). A partial path replaces a whole subtree. Untouched
fields keep their specs; a replaced field takes the new value's spec.
Source code in probpipe/core/named_tree.py
rename(renames=None, /, **keyword_renames)
¶
Return a same-family tree with the given nodes renamed or moved, old -> new.
Acts on the nodes within the tree, leaves or whole subtrees; the object
itself is relabeled by with_label on the tracked value types. Each key is
the exact path of a node, so a keyword addresses a top-level node and the
positional renames any node. Each target is the node's new exact path,
so a bare name is a top-level path::
t.rename(mu="loc") # rename a top-level node
t.rename({"g/mu": "g/loc"}) # rename a node within g
t.rename({"g/mu": "mu"}) # move it out of g
t.rename({"mu": "g/mu"}) # move it into g
The renames apply simultaneously: every key is resolved against the original tree, so swaps are well-defined, and a node below a moved node moves with it unless it has a target of its own. A node whose target has its source's parent, and none of whose ancestors moves, is renamed in place and keeps its position. Every other node is moved: it is appended at the end of its new parent's children, in the order the renames are given, and a missing parent is created and appended the same way. A group that the moves leave without a field is removed. The leaf objects are unchanged, and the mapping interface stays keyed by full path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
renames
|
Mapping of str to str
|
The new path of each node, keyed by the node's path. |
None
|
**keyword_renames
|
str
|
The new path of each top-level node, keyed by the node's name. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A tree of the same family over the same leaf objects. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a key is not the path of a node. |
TypeError
|
If a key or a target is not a string, such as a tuple of names. |
ValueError
|
If a key or a target is empty or has an empty name, two keys rename the same node, no renames are given, a node moves into its own subtree, two targets are equal or one lies inside the other, or a target collides with a node that remains. |
Source code in probpipe/core/named_tree.py
Linear operators¶
MultivariateNormal accepts a linear operator as its cov, and the _cov method of a family that claims SupportsCovariance returns one.
probpipe.linalg.LinOp()
¶
Bases: ABC
Abstract base class for a linear operator.
Concrete subclasses must provide shape, dtype, matvec, rmatvec, and
to_dense. LinOp provides convenience arithmetic (matmul, add, mul, ...)
that constructs composed operators without densifying where possible. The
matvec/rmatvec and matmat/rmatmat methods provide the option to implement matrix-vector
and matrix-matrix products without densifying the operator.
Flags are restricted to ALLOWED_FLAGS. Use .flags (frozenset) to inspect.
Attributes:
_flags: a set of semantic flags (e.g., "symmetric", "positive_definite").
See add_flag, has_flag.
Source code in probpipe/linalg/linear_operator.py
shape
abstractmethod
property
¶
Return (n_out, n_in).
dtype
abstractmethod
property
¶
Return the dtype of this operator's elements.
raw
abstractmethod
property
¶
The stored parameterization, such as a dense operator's matrix or a lazy composite's operands.
is_dense
property
¶
Default is False; DenseLinOp overrides to True
flags
property
¶
Return frozenset of current flags (read-only view).
T
property
¶
Return a transposed operator view.
__init_subclass__(**kwargs)
¶
Refuse a subclass on which raw is anything but a property.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
The class keywords, passed on to the next class in the MRO. |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in probpipe/linalg/linear_operator.py
to_dense()
abstractmethod
¶
Return dense array representation of the operator.
Implementations may raise if dense form is unaffordable.
apply(x)
¶
matvec(x)
¶
rmatvec(x)
¶
matmat(X)
¶
rmatmat(X)
¶
solve(b, **kwargs)
¶
Solve A x = b; default uses dense fallback.
Source code in probpipe/linalg/linear_operator.py
cholesky(lower=True, **kwargs)
¶
Return triangular LinOp L (lower) or L.T (upper) such that A = L @ L.T.
Defaults to densifying the operator and then computing the Cholesky decomposition. Subclasses may return other valid LinOp types that are more structured than TriangularLinOp; for example, DiagonalLinOp.
Source code in probpipe/linalg/linear_operator.py
to_cholesky_representation(lower=True, **kwargs)
¶
Return representation of self in terms of its Cholesky factor.
In general, this represents an alternative represetation of the operator. Defaults to computing the Cholesky factor and wrapping the result in CholeskyLinOp. Subclasses may return other valid LinOp types when more structure is present; for example, DiagonalRootLinOp.
Source code in probpipe/linalg/linear_operator.py
diag()
¶
logdet()
¶
Return log determinant; default uses dense fallback. Raises if sign <= 0
Source code in probpipe/linalg/linear_operator.py
trace()
¶
add_flag(flag)
¶
Attach a semantic flag (must be one of ALLOWED_FLAGS).
remove_flag(flag)
¶
has_flag(flag)
¶
__matmul__(other)
¶
__repr__()
¶
The class, the shape and the dtype, and a composite's operands.
Source code in probpipe/linalg/linear_operator.py
probpipe.linalg.DenseLinOp(arr, copy=True)
¶
probpipe.linalg.DiagonalLinOp(diag, copy=True)
¶
Bases: LinOp
Diagonal operator represented by a 1D array of diagonal entries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diag
|
array - like
|
The diagonal entries. An array of higher rank is flattened. |
required |
copy
|
bool
|
Whether to store a copy of the flattened entries. |
True
|
Source code in probpipe/linalg/linear_operator.py
raw
property
¶
The stored diagonal.
solve(b, **kwargs)
¶
For consistency with jnp.linalg.solve(), b can be (n,) or (n,k).
Source code in probpipe/linalg/linear_operator.py
cholesky(lower=True, **kwargs)
¶
Note that lower has no effect on Cholesky decomposition of diagonal matrix
Source code in probpipe/linalg/linear_operator.py
probpipe.linalg.TriangularLinOp(tri, *, lower=True, copy=True)
¶
Bases: LinOp
Triangular operator represented by lower or upper triangular matrix L (2D array).
The operator interprets stored matrix tri so that:
- if lower==True: stored tri is lower triangular and operator is L @ x
- if lower==False: stored tri is upper triangular and operator is U @ x
Source code in probpipe/linalg/linear_operator.py
raw
property
¶
The stored triangular matrix; its flags state which triangle it is.
solve(b, *, unit_diagonal=False, **kwargs)
¶
Solve triangular system Lx=b or Ux=b.
Source code in probpipe/linalg/linear_operator.py
probpipe.linalg.CholeskyLinOp(root)
¶
Bases: RootLinOp
Positive-definite operator represented by a Cholesky factor.
A lower root L represents A = L @ L.T; an upper root U
represents A = U.T @ U.
Source code in probpipe/linalg/linear_operator.py
raw
property
¶
The stored Cholesky factor, L of A = L @ L.T or U of A = U.T @ U.
matvec(x)
¶
Return A @ x for the represented SPD operator.
rmatvec(x)
¶
matmat(X)
¶
Return A @ X without densifying the Cholesky factor.
rmatmat(X)
¶
diag()
¶
to_dense()
¶
Return the dense matrix represented by the Cholesky factor.
solve(b, **kwargs)
¶
Linear solve using forward backward triangular substitution
For lower roots, compute A^{-1} b = (L @ L.T)^{-1} b by
solving through L and then L.T. For upper roots, compute
A^{-1} b = (U.T @ U)^{-1} b by solving through U.T and
then U.
Source code in probpipe/linalg/linear_operator.py
probpipe.linalg.RootLinOp(root)
¶
Bases: LinOp
A positive-semidefinite operator A = S @ S.T, stored as its root S.
A linear operator A represented by its square root S such that A = S @ S.T A is guaranteed to be symmetric positive semidefinite, but not necessarily positive definite.
Source code in probpipe/linalg/linear_operator.py
raw
property
¶
The stored root S of A = S @ S.T, an operator.
solve(b, **kwargs)
¶
Linear solve using forward backward substitution
To compute A^{-1}b = (S @ S.T)^{-1}b first compute y = S^{-1}b then S.T^{-1}y.
Source code in probpipe/linalg/linear_operator.py
probpipe.linalg.DiagonalRootLinOp(root)
¶
Bases: DiagonalLinOp
A diagonal operator A = S @ S.T, stored as its diagonal root S.
A linear operator A represented by its diagonal square root S = diag(s1, ..., sd) such that A = S @ S.T = diag(s1^2, ..., sd^2). A is guaranteed to be symmetric positive semidefinite, and is strictly positive definite if all entries of all of the si are non-zero.
Source code in probpipe/linalg/linear_operator.py
raw
property
¶
The stored diagonal root S of A = S @ S.T, an operator.
cholesky(lower=True, **kwargs)
¶
Note that lower has no effect on Cholesky decomposition of diagonal matrix