AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Distributions and families¶
This page documents the distribution classes, the factories that build a law or a kernel from functions, the capabilities a distribution claims, and the families ProbPipe ships.
The distributions over functions and over distributions are on Random functions, and the operations on a distribution, such as sample and mean, are on Operations.
Distributions¶
distribution(*, sample=None, log_prob=None, unnormalized_log_prob=None, event_spec, output_name=None, label=None)
¶
Build a Distribution from a sampling function, a log-density, or both.
sample(key) returns one draw at a PRNG key, at the kind the event
spec names, as an array for an array event or a mapping or
Record for a record event. log_prob(value) returns the normalized
log-density of one value as a real scalar, and
unnormalized_log_prob(value) returns one up to an additive constant. A density receives an array for an array event, a
Record for a record event, and the value itself for any other event.
The law claims the capability each function given realizes:
- sample:
SupportsSampling; - log_prob:
SupportsLogProb, which provides the unnormalized density too; - unnormalized_log_prob:
SupportsUnnormalizedLogProb.
A law of a density alone is therefore unnormalized, and sample,
convert, and condition_on normalize it through the
inference-method registry.
A non-empty sample shape maps sample over keys split from the draw's key
with jax.vmap. A sampler that does not trace in JAX, such as one that
calls NumPy or an external program, and a sampler of an event that is not
numeric are called at one key at a time instead, and their draws stack into
the batch form of the event's kind. A density scores a batch of values
along its leading axes, with jax.vmap when it traces.
Construction draws nothing and scores no value. It traces each function
once, without values, to learn whether JAX can trace it: the abstract draw
of sample must unify with event_spec, which it completes by filling a
pending type and setting a dtype it leaves unset, and each
density must return a real scalar at a stand-in of one value of the event.
A function that does not trace is read nothing from, and it makes the law
run one value at a time. Every law built from the same code with captured
values of the same shapes and dtypes, such as the law a kernel builds at
each given value, shares that trace, so the trace runs once, unless the
function reads a captured value, as jnp.zeros(int(n)) does. A function
that draws from NumPy's or Python's global random generator is treated as
one that does not trace, with a warning.
A kernel of a simulator samples and has no density::
simulator = conditional_distribution(
lambda rate: distribution(
sample=lambda key: jax.random.poisson(key, rate, (10,)),
event_spec=NumericArraySpec((10,), jnp.int32, non_negative_integer),
output_name="y",
),
label="simulator",
given_spec={"rate": NumericArraySpec((), jnp.float32, positive)},
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
callable
|
|
None
|
log_prob
|
callable
|
|
None
|
unnormalized_log_prob
|
callable
|
|
None
|
event_spec
|
OutputSpec or TermSpec
|
The spec of one draw. An |
required |
output_name
|
str
|
The name of the output of a whole-term event declared by a bare spec other than a record; required for one, and refused with any other event_spec. |
None
|
label
|
str
|
The law's label, |
None
|
Returns:
| Type | Description |
|---|---|
Distribution
|
The law, which claims the capability of each function given. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is not a non-empty string; if no function is given, a given function is not callable, or both densities are given; if event_spec is not a spec; if output_name is missing for a whole-term event or given for another; or if event_spec has a pending type and no sampler that traces fills it. |
ValueError
|
If the abstract draw of sample does not conform to event_spec, or a density that traces returns anything but a real scalar. |
Source code in probpipe/distributions/_from_functions.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 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 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | |
Distribution(event_spec, *, label=None, _provenance=None, _annotations=None)
¶
Bases: TrackedTerm, Annotated, ABC
Abstract base for all ProbPipe distributions.
Every distribution is a tracked term: it is
TrackedTerm (a label and a write-once
provenance) and
Annotated (free-form
annotations). A family's constructor takes the
name of its event's output first and an optional label=, which defaults to
the family's class name, so Normal("mu", 0.0, 1.0) is labeled
Normal over the output mu; any other law's label defaults to
ℙ, and a joint that & merges is labeled by its operands' labels.
Every transform preserves the label; only with_label replaces it. str(d)
returns the law's notation, its label followed by its signature, as
prior(mu), and the repr reads as a call of the constructor, with
label= where a caller gave a label other than the default, as
Normal('mu', loc=0.0, scale=1.0, label='prior').
Sampling and expectation capabilities are provided by the
SupportsSampling protocol.
The event spec. A law stores one DistributionSpec, its
spec, whose event_spec is the output spec of one
draw. The fields of a bare RecordSpec are the outputs, and an
OutputSpec names the output of a whole-term event, as
OutputSpec(mu=spec). event_shape reads the event spec, and a
law whose event spec is numeric also has the views of
NumericDistribution; none of them is stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_spec
|
OutputSpec or RecordSpec
|
The output spec of one draw, completed as above. |
required |
label
|
str
|
The law's label, a non-empty string, |
None
|
_provenance
|
Provenance
|
The provenance of the law that a reconstruction rebuilds. By default the
provenance stays unset until |
None
|
_annotations
|
Mapping[str, Any]
|
The annotations of the law that a reconstruction rebuilds, copied into the
law's own store. By default |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is not a non-empty string, or event_spec is neither an
|
ValueError
|
If event_spec leaves its type unspecified. |
Source code in probpipe/distributions/_distribution.py
raw
property
¶
This law detached from the workflow, under its label and event spec.
A law is represented by itself, so its raw form is a copy that shares its representation and carries no provenance, no annotations, and no reference to a container or a parent, such as a batch it was an element of or a law it is a copy of. A coupled marginal returns the raw form of its parent's marginal at its path instead, and a backend adapter its wrapped backend distribution.
Every read returns the same copy, which refuses provenance, since every
reader shares it. with_label gives a copy of it that can carry
provenance.
spec
property
¶
The law's term spec, the one stored source of its event spec.
event_spec
property
¶
The output spec of one draw, read from spec.
event_shape
property
¶
The shape of one draw, defined only when a draw is a single array.
For any other law the attribute is absent, so hasattr(law,
"event_shape") is False.
Raises:
| Type | Description |
|---|---|
AttributeError
|
If a draw is not a single array, a one-field record included. |
ValueError
|
If the declared shape has unbound dimensions. |
diagnostics
property
¶
Structured view over diagnostic results stored in annotations.
Returns None if no diagnostics have been computed yet.
Inference backends and the diagnostics subsystem store posterior
metadata in an xarray.DataTree attached to the distribution as
its annotations. The
expected layout is::
posterior._annotations
├── arviz/ # ArviZ-compatible data and raw inputs
│ ├── posterior
│ ├── sample_stats
│ ├── observed_data
│ ├── posterior_predictive
│ └── log_likelihood
└── diagnostics/ # ProbPipe-computed results and metadata
├── mcmc # rhat, ess_bulk, ess_tail, mcse, ...
└── runs # on-demand diagnostics such as ppc, loo, spc
├── ppc
├── loo
└── spc
The /arviz/ subtree is intended to be passed to ArviZ functions
and to hold raw diagnostic ingredients such as sampler statistics,
posterior predictive samples, and pointwise log likelihoods. In ArviZ
1.0+, this is an ArviZ-compatible DataTree rather than the older
InferenceData representation.
This property returns a structured Python accessor over the
/diagnostics/ subtree only. It is distinct from the ArviZ-compatible
data used for plotting or ArviZ computations.
In other words::
posterior.diagnostics
# structured ProbPipe view over posterior.annotations["diagnostics"]
posterior.annotations["arviz"]
# the ArviZ-compatible xarray DataTree
Examples:
::
posterior = condition_on(model, data)
# MCMC diagnostics mutate posterior._annotations in place and return None.
add_mcmc_diagnostics(posterior)
posterior.diagnostics.rhat
# {"intercept": 1.001, "slope": 1.002}
posterior.diagnostics.warnings
# []
posterior.diagnostics.runs
# []
# Posterior predictive checks are stored under diagnostics/runs/ppc.
add_ppc(
posterior,
test_fns=[...],
observed_data=y,
kernel=likelihood,
)
posterior.diagnostics.ppc.result
# {"var_mean_ratio": {"p_value": 0.43, "observed": 3.2}}
posterior.diagnostics.runs[0].result
# {"p_value": {"var_mean_ratio": 0.43}, ...}
posterior.diagnostics.runs[0].plot_fn
# "" unless the run wrote ArviZ-compatible plotting inputs
Notes
The diagnostics accessor is read-only. Diagnostic functions such as
add_mcmc_diagnostics and add_ppc are responsible for writing
diagnostic results into posterior._annotations.
notation
property
¶
The law's label followed by its signature, as prior(mu), which str() returns.
The signature lists the event outputs in declaration order, joined
by ", ", then ; and the paths the law holds fixed at given
values when it holds any, as model(mu; y). The label is grouped so
the call applies to all of it, as in (lik·prior)(y). A product
without a label reads factor by factor, as lik(y | mu)·prior(mu),
and the law of a function lifted over laws reads as the function at
draws of its inputs, as f(beta ~ model; y). The notation is a
rendering of the law's expression, made each time it is shown, which
shows at most the current config.notation.max_depth nested levels.
No operation reads the notation.
__getattr__(name)
¶
Resolve a view of NumericDistribution for a numeric law of another class.
Python calls this only when ordinary lookup fails. A law whose event spec is numeric has the views of the marker whatever its class, so they resolve through the marker, and any other missing attribute raises as usual.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The attribute that ordinary lookup did not find, such as |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The value of the marker's view name for this law. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If name is not an attribute of the law, a view of the marker on a law whose event spec is not numeric included. |
Source code in probpipe/distributions/_distribution.py
with_label(label)
¶
Return a copy of this law under a new label.
The copy shares the representation and records the relabeling in its
provenance, as TrackedTerm.with_label states. It is this law
under a new label, so a lift draws it together with this law (V.5).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The new label, a non-empty string. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A copy of the same class under label; the original is unchanged. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is not a non-empty string. |
Source code in probpipe/distributions/_distribution.py
with_dim_sizes(**sizes)
¶
Bind named symbolic dimensions of the event spec.
The result is this law with its dimensions bound, so a lift draws it together with this law (V.5).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**sizes
|
int
|
Sizes for free dimensions of the event spec. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A copy of the same class and label whose event spec has the sizes substituted; the original is unchanged. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a name is not a free dimension of the event spec, one an earlier call bound included, or a size is negative. |
TypeError
|
If a size is not an integer. |
Source code in probpipe/distributions/_distribution.py
with_dim_names(**names)
¶
Rename symbolic dimensions of the event spec, simultaneously.
The result is this law under the new dimension names, so a lift draws it together with this law (V.5).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**names
|
str
|
New names keyed by old; names that are not free are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A copy of the same class and label whose event spec has the dimensions renamed; the original is unchanged. |
Source code in probpipe/distributions/_distribution.py
rename(renames=None, /, **keyword_renames)
¶
Rename or move nodes of the event spec by their paths, old -> new.
The result is this law with OutputSpec.rename applied to
its event spec. A path starts with an output's name, and the form is
kept, so a whole term's output is renamed in place with the term's
fields under it. The law is unchanged: a draw of the result is a draw of
this law carrying the new names. Renaming a whole term's output alone
changes only the event spec, so the result is a copy of the same class.
A factored law renames through its factors where they can carry the
rename, and the result is the factored joint of the renamed factors over
the same graph. A rename that gathers outputs under a new node
regroups the factors that produce them into a packaged sub-joint, one
factor of the result whose event is the node. A family whose parameters
carry the event's paths rebuilds itself under the new paths: an
empirical law over records returns the empirical law of its atoms with
their fields at the new paths, under the same weights. Any other rename
that changes the path of a field of a record draw, including a gathering
whose groups condition on one another in a cycle, returns a law that
holds this one and renames values at its boundary: draws, moments, and
marginals on the way out, and scored values, givens, and paths on the
way in. A lift draws the result together with this law, as it draws a
view with its parent (V.5).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
renames
|
Mapping[str, str]
|
The new exact path of each node, keyed by the node's exact path. |
None
|
**keyword_renames
|
str
|
Further renames, keyed by paths that are identifiers. |
{}
|
Returns:
| Type | Description |
|---|---|
Distribution
|
The renamed law under the same label; the original is unchanged. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a key is not a path of the event spec. |
TypeError
|
As |
ValueError
|
As |
Source code in probpipe/distributions/_distribution.py
__getitem__(paths)
¶
The law itself at a whole term's output, or the coupled marginal at a path or a list of paths.
A whole-term law is itself under its output, so d[name] returns
d; the output is fixed at construction, so after with_label the
law is still addressed by it. Any other event path, an output that is a
record's field or a path below a whole record's output, gives the
CoupledMarginal of the node there, which holds a reference to this law and
gives the node whole under the path's last name. A list or a tuple of
paths gives the view over the record that keeps each node at its own
path, in this law's order, so grouped["a", "g/c"] draws records
{a, g: {c}}. A tuple is read as a list of paths; a nested path is
written with /.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
str, or list or tuple of str
|
An event path, which starts with an output's name, or a list of event paths to view jointly. |
required |
Returns:
| Type | Description |
|---|---|
Distribution
|
This law itself, or a |
Raises:
| Type | Description |
|---|---|
KeyError
|
If this law is over a record and a path is not one of its paths. |
TypeError
|
If paths is neither a string nor a list or tuple of strings, or this law is over a value with no paths, such as an array. |
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/distributions/_distribution.py
__contains__(path)
¶
Whether path is a str and self[path] gives a law: an event path, or a whole term's output.
__mul__(other)
¶
Refuse * between distributions. Use & to merge them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If other is a distribution or a conditional distribution. |
Source code in probpipe/distributions/_distribution.py
__bool__()
¶
Refuse a truth value, so a and b raises. Use a & b to merge.
Raises:
| Type | Description |
|---|---|
TypeError
|
Always: a distribution has no truth value. |
Source code in probpipe/distributions/_distribution.py
__and__(other)
¶
The joint of this law and other, merged conditional-first.
The left operand may condition on what the right produces, so lik &
prior reads as p(y | β) · p(β). The result is a
FactoredDistribution when no given is left unmet and a
FactoredConditionalDistribution otherwise, flattened over the
operands' factors. The joint is a product that no one gave a label, so
its label joins the operands' labels with ·, as lik·prior, and
its notation joins its factors' notations, as lik(y | mu)·prior(mu).
Its provenance records the operation & with this law and other
as its parents, in that order and as written rather than flattened, so
print(joint.provenance) includes the lineage of both operands. It
records none where Provenance.create records none, as under the
provenance mode off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Distribution or ConditionalDistribution
|
The right operand, whose outputs this law's factors may condition on. |
required |
Returns:
| Type | Description |
|---|---|
FactoredDistribution or FactoredConditionalDistribution
|
The joint, or |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an operand's draws are distributions or batches, which have no outputs to merge by name, until they are wrapped under a name. |
ValueError
|
If the two operands are coupled, as two marginals of one law are, an output is produced twice, the right operand consumes an output the left produces, or matched specs do not unify. |
Source code in probpipe/distributions/_distribution.py
from_batched_params(*, label, batch_shape=None, **batched_params)
classmethod
¶
The separate laws of this class at batched parameters, one per batch position.
Each parameter's leading axes are the batch axes, and the law at a position is this class at that position's parameters. The form of the result is not yet decided, so the method raises.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The batch's label. |
required |
batch_shape
|
tuple of int
|
The batch axes, inferred from the parameters when omitted. |
None
|
**batched_params
|
Any
|
This class's constructor arguments, with the batch axes leading. |
{}
|
Returns:
| Type | Description |
|---|---|
DistributionBatch
|
The batch of these laws under the label label, with the batch axes as its batch shape. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always. |
Source code in probpipe/distributions/_distribution.py
__str__()
¶
__repr__()
¶
A call of the law's public constructor, followed by the paths the law holds fixed.
The name of a whole-term event's output and the family parameters come
first, as the constructor takes them, then label= where the label
differs from the constructor's default, as
Normal('mu', loc=0.0, scale=1.0, label='prior'), and
event_spec= where the event spec differs from the default. The
paths the law holds fixed follow as fixed=('y',).
Source code in probpipe/distributions/_distribution.py
NumericDistribution(event_spec, *, label=None, _provenance=None, _annotations=None)
¶
Bases: Distribution
The marker of a law whose event spec is numeric, with its views.
isinstance(d, NumericDistribution) holds if and only if
d.event_spec.term_spec is a NumericSpec,
so a draw implements Numeric and the flat-vector interface applies. A
class whose every instance is numeric may inherit the marker, and
construction checks that each instance declares a numeric event.
Every numeric law has the views below, whatever its class: a class that
inherits the marker has them directly, and any other numeric law resolves
them through the marker. A law whose event spec is not numeric has none of
them. Like event_shape, they read the event spec and are never stored.
The marker is not a dispatch type. Registering a method for it raises
TypeError, since selection by class would miss a numeric law whose class
does not inherit it.
Source code in probpipe/distributions/_distribution.py
dtypes
property
¶
The declared dtype of each array leaf of a draw, keyed by leaf path.
supports
property
¶
The declared support of each array leaf of a draw, keyed by leaf path.
dtype
property
¶
The dtype every array leaf shares, or None when they differ or there are none.
support
property
¶
The support every array leaf shares, or None when they differ or there are none.
supports tells leaves that differ from leaves that are unset. Supports
whose comparison needs a traced value, as under jit, count as different.
EmpiricalDistribution(atoms, weights=None, *, output_name=None, label=None, level=None, event_spec=None)
¶
Bases: Distribution, SupportsSampling, SupportsExpectation, SupportsMarginals
The law of a finite, possibly weighted set of atoms of any event type.
The atoms are given in the event's batch form, such as a RecordBatch or
an OpaqueBatch, or as an array whose leading axis indexes array atoms.
Every batch axis indexes atoms, in the row-major order positional indexing
reads. A batch is stored as given and keeps its own levels, which
with_level_names renames. An array is stored as a NumericArrayBatch
labeled by the name of the law's output, on one level named by level,
which defaults to that name. The weights are normalized and default to
uniform. The law's label is ℙ unless label gives another.
The event spec. The fields of record atoms are the law's outputs, and
any other atoms form a whole-term event whose one output is named
output_name. An event_spec names the outputs and their form in place of
output_name. OutputSpec.with_term_spec completes it with the atoms'
spec: where its type is unspecified it takes that spec, and a declared type
must unify with it.
Renaming. For record atoms, rename returns an
EmpiricalDistribution with the same label and weights, whose atoms are
these atoms with each field at its new path, on the same levels and in the
same order.
Capabilities.
========================== ===================================================
capability realized by
========================== ===================================================
_sample weighted resampling of the atoms
_expectation the weighted mean of f over the atoms, exact
_marginal the empirical law of the projected atoms under the
same weights, exact at every event path
_mean, _variance the weighted moments of a numeric event
_cov the weighted covariance of a numeric event as a
DenseLinOp over its flat coordinates
_quantile the generalized inverse inf{x : F(x) >= q} of
each coordinate's weighted CDF, for a numeric event
========================== ===================================================
An instance claims the moments when its event is numeric: an array, a record of arrays, or a batch of either. The moments of a batch-valued event are elementwise: the mean, the variance, and the quantiles at each position of the event's levels are those of the atoms' entries at that position. Its covariance is over the flat coordinates of one draw, which run over the event's batch axes and then the element's own axes. The law claims no density, since an empirical measure has none in general. Every result that is shaped like a draw is in the draw's raw form, so a record event's draw, moment, or quantiles are a nested mapping of raw leaves, and each leaf of a batch-valued event's mean has the event's batch axes leading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms
|
Batch or Array
|
The atoms in the event's batch form, or an array of array atoms along its leading axis. |
required |
weights
|
Array or Weights
|
Nonnegative weights with a positive sum, normalized at construction:
flat, one per atom in the row-major order of the atom axes, or shaped
like those axes, excluding any event batch axes. A |
None
|
output_name
|
str
|
The name of a whole-term event's output, required for atoms that are not records unless event_spec names it, and refused for record atoms. |
None
|
label
|
str
|
The law's label, |
None
|
level
|
str
|
The name of the one level a plain array's atoms lie on. It defaults to the name of the law's output. |
None
|
event_spec
|
OutputSpec
|
The output spec of one draw, completed with the atoms' spec. For a
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is not a non-empty string, atoms is neither a batch of a
stored kind nor a numeric array, output_name is missing for atoms that
are not records or given for record atoms, level is not a string or
is given with a batch of atoms, event_spec is not an |
ValueError
|
If atoms holds no atom or is a 0-d array, the weights do not number one per atom or are negative or sum to zero, output_name is not a valid output name, level is not a valid level name, or event_spec names another output than output_name or declares a type that does not unify with the atoms' spec, or a batch-valued event's levels do not trail at least one atom level or include the level that array atoms lie on, or nested event batches repeat a level name. |
Examples:
>>> import jax.numpy as jnp
>>> law = EmpiricalDistribution(
... jnp.array([0.0, 1.0, 3.0]), jnp.array([1.0, 1.0, 2.0]), output_name="theta"
... )
>>> (law.label, list(law.event_spec.outputs))
('ℙ', ['theta'])
>>> law.atoms.level_names
('theta',)
>>> float(law._mean())
1.75
Source code in probpipe/distributions/_empirical.py
DistributionBatch(elements, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)
¶
Bases: _ObjectBatch[Distribution]
N separate distributions sharing one event spec, along batch axes.
A DistributionBatch is a collection of separate measures, distinct from
one joint law over a product space, as a batch of draws is distinct from one
record of many fields. It is the batch form of DistributionSpec-valued
terms, and what a sweep of a kernel over a batch of given values produces.
The batch stores its elements, and batch[i] is a view of the stored law:
a copy under the label derived from the position, such as "laws[law=1]",
sharing the stored law's representation, whose provenance records the batch
and the stored law. A lift groups an element with its stored law, so every
access of one element draws together.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elements
|
numpy.ndarray or iterable of Distribution
|
The laws, 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. Defaults to a list of its first eight laws in
row-major order over every batch axis, each in its notation, followed
by |
None
|
element
|
DistributionSpec
|
The spec every element satisfies. Defaults to the first element's spec, so the elements share its event spec. |
None
|
axes_per_level
|
int or sequence of int
|
How many axes each level holds, outermost first (a single int is one level's count). Defaults to one axis per level. |
None
|
provenance
|
Provenance
|
How this batch was produced. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If element is not a |
ValueError
|
If elements is empty and element is omitted, or the axes and level names disagree as for every batch. |
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/distributions/_batches.py
event_spec
property
¶
The event spec the elements share, a view on spec.
__str__()
¶
The batch's notation and its levels, as schools(effect) over school.
The notation is that of one law under the batch's label, and a batch
that a function lifted over laws gives reads as the call, as
effect_of(mu ~ prior, tau) over tau.
Source code in probpipe/distributions/_batches.py
probpipe.distributions.CoupledMarginal(parent, path)
¶
Bases: Distribution
The law of the node at one event path of a parent law, or of the nodes at a list of paths.
d[path] returns a CoupledMarginal for a node below the law's whole term,
and d[paths] for a list or a tuple of paths; it is never constructed by
hand. The coupled marginal holds a reference to its parent rather than a standalone law,
so sibling coupled marginals co-sample from one parent draw and the correlation between
them is preserved. For one path, its event spec is the parent's schema at
the path, the leaf or group whole, under an output named by the path's
last name. For a list of paths, its event spec is the positional form over
the record that keeps each node at its own path, in the parent's order
whatever the order of the list, so grouped["g/e", "a"] draws records
{a, g: {e}}.
The coupled marginal displays as the standalone marginal at its path does, and its repr
names the class and the path, which distinguishes it from that marginal.
It is labeled as marginal labels the marginal there (VI.8), so
model["y"] reads as model(y), and model["mu"] at the factor
prior reads as prior(mu). A coupled marginal of the whole events of several
factors reads factor by factor, as a(a)·b(b) (notation). The
coupled marginal holds the paths its parent holds fixed, after those of the one factor
it is when it is one.
Its capabilities are derived from the parent's, one by one:
====================================== ========================================
capability on the coupled marginal available when
====================================== ========================================
_sample the parent samples
_mean, _variance the parent has the moment, or has marginals
and reports it for its marginal at the path
_cov, _quantile as for the mean, and the node is numeric
_expectation the parent has it
_log_prob, _unnormalized_log_prob the parent has marginals and reports the
density for its marginal at the path; the
guard asks that marginal be exact
_marginal at a sub-path the parent has marginals
_condition_on a sub-field the parent's conditioning capability
====================================== ========================================
Each derived capability carries the parent's guard for the call it makes.
A moment the parent does not claim is the moment of the parent's exact
marginal at the path, under the parent's marginal guard and then the
marginal's guard of the moment, so a coupled marginal of a dependent joint at a root
factor takes the factor's moments. The projection rows are exact whenever
the parent's answer is, and only sampling requires the parent to sample.
The parent reports what its marginal at the path claims through
_marginal_capabilities, and a parent that defines none reports its own
claims; the coupled marginal reads the report once, at construction.
The coupled marginal's raw is the raw form of the parent's marginal at the path,
parent._marginal(path).raw: the backend object where the marginal
has one, such as the TFP distribution of a TFP family, and the standalone
law otherwise. with_dim_sizes and with_dim_names apply to the
parent and return the coupled marginal of the result at the same path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent
|
Distribution
|
The law whose event the coupled marginal reads. |
required |
path
|
str, or list or tuple of str
|
An event path of parent, a slash path that starts with an output's name, or a list of them. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If parent is over a record and a path is not one of its paths. |
TypeError
|
If parent is not a |
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/distributions/_views.py
parent
property
¶
The law this coupled marginal reads, which sibling coupled marginals share.
path
property
¶
The event path of the parent that this coupled marginal reads, or the tuple of them in the parent's order.
raw
property
¶
The raw form of the parent's marginal at the path, parent._marginal(path).raw.
Every read returns the same object, resolved on the first read. A standalone law refuses provenance, since every reader shares it.
Returns:
| Type | Description |
|---|---|
Any
|
The marginal's backend object where it has one, such as the TFP
distribution of a TFP family. Otherwise the marginal standalone: a
standalone law with no reference to the parent, and no provenance
or annotations, which carries the coupled marginal's expression, so it is
labeled as |
Raises:
| Type | Description |
|---|---|
ResolutionError
|
If the parent has no exact marginal at the path. The error is not
an |
__getitem__(paths)
¶
This coupled marginal itself, or the law at a path or a list of paths of the coupled marginal.
A tuple is read as a list of paths; a nested path is written with /.
A path of a coupled marginal over one path starts with its output's name, so
d["a"]["a/b/c"] reads the node that d["a/b/c"] reads. A list of
paths of the coupled marginal gives the law whose event keeps each node at its path
of the coupled marginal. A coupled marginal over a list of paths keeps its parent's paths, so
d["a", "g/c"]["g/c"] reads the node that d["g/c"] reads. The
result is labeled as the marginal of this coupled marginal at paths is labeled
(marginal), and it holds the paths this coupled marginal holds fixed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
str, or list or tuple of str
|
An event path of the coupled marginal, or a list of them. |
required |
Returns:
| Type | Description |
|---|---|
Distribution
|
This coupled marginal itself, or a law that reads the parent. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the coupled marginal is over a record and a path is not one of its paths. |
TypeError
|
If paths is neither a string nor a list or tuple of strings, or the coupled marginal is over a value with no paths, such as an array. |
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/distributions/_views.py
with_dim_sizes(**sizes)
¶
Bind named symbolic dimensions in the parent, and coupled marginal the result at the same path.
The coupled marginal's event spec is the parent's schema at the path, and a schema is one dimension scope, so a dimension binds wherever the parent declares it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**sizes
|
int
|
Sizes for free dimensions of the coupled marginal's declaration. |
{}
|
Returns:
| Type | Description |
|---|---|
CoupledMarginal
|
The coupled marginal, under the same label, of the parent with the sizes bound. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a name is not a free dimension of the coupled marginal's declaration. |
Source code in probpipe/distributions/_views.py
with_dim_names(**names)
¶
Rename symbolic dimensions in the parent, and coupled marginal the result at the same path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**names
|
str
|
New names keyed by old; names that are not free are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
CoupledMarginal
|
The coupled marginal, under the same label, of the parent with the dimensions renamed. |
Source code in probpipe/distributions/_views.py
__repr__()
¶
CoupledMarginal(parent, path=...), followed by .with_label(...) for a coupled marginal under another label.
The constructor gives a coupled marginal the label of its parent's marginal at its
path, so a coupled marginal that with_label relabeled reads as the constructor
call relabeled. The parent's repr shows any paths it holds fixed.
Source code in probpipe/distributions/_views.py
Conditional distributions¶
conditional_distribution(fn=None, /, *, label=None, given_spec=None, event_spec=None)
¶
Build a ConditionalDistribution from a function of its given values that returns a law.
Each parameter of the function is an input, declared by its entry in given_spec or else by its annotation, which is then a term spec. A parameter with a default is an optional input, which its default's value declares when neither does. Construction evaluates the function once, abstractly, at stand-ins of the required inputs' types and at the defaults of the optional ones, and reads the law it returns: its event spec is the kernel's, unless event_spec declares one that agrees with it, and the kernel claims conditional sampling and the conditional density exactly when that law claims sampling and a density, each with the law's guard. Binding every required input calls the function with each value as the argument of that name, at the kind its input declares, and with its default for each optional input left unbound, and returns the law the call returns; binding fewer inputs returns the kernel over the rest.
The kernel is labeled label, or after the function's __name__, and
ℙ for a lambda. The call form takes the function first::
likelihood = conditional_distribution(
lambda mu, tau: Normal("y", mu, tau), label="lik", given_spec={"mu": real, "tau": scale}
)
An optional input holds a constant of the model. In a joint, a factor that produces an output of its name meets it, so one kernel serves a model with the default and a model with a prior on the input::
counts = conditional_distribution(
lambda r, n0=50.0: Poisson("y", n0 * jnp.exp(r)),
label="counts",
given_spec={"r": real},
)
fixed = counts & Normal("r", 0.0, 1.0) # n0 is 50
uncertain = counts & (Normal("r", 0.0, 1.0) & LogNormal("n0", 4.0, 0.3))
and the decorator form labels the kernel after the function, or as given::
@conditional_distribution(given_spec=prior.event_spec.outputs)
def y(population, groups, sigma=1.0):
return Normal("y", population["mu"] + population["tau"] * groups["theta"], sigma)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
callable
|
The function of the given values that returns a law; without it, the result is a decorator. |
None
|
label
|
str
|
The kernel's label. Defaults to the function's |
None
|
given_spec
|
InputSpec, Mapping, RecordSpec, or OutputSpec
|
The specs of some or all inputs, keyed by parameter. |
None
|
event_spec
|
OutputSpec or TermSpec
|
The event spec, which must name the outputs of the returned law and unify with its type. A bare term spec other than a record declares the returned law's one output. |
None
|
Returns:
| Type | Description |
|---|---|
ConditionalDistribution or callable
|
The kernel, or a decorator that builds it from a function. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If fn is a string, since the label is the keyword label; if label is not a non-empty string; if a parameter without a default declares no term spec, a parameter is variadic or positional-only, or given_spec names a key that is not a parameter; if a required input is neither an array nor a record of arrays, or declares free dimensions; or if the function returns something other than a law. |
ValueError
|
If event_spec is a bare term spec other than a |
Notes
The function computes the kernel's conditional draws and densities, so it
must be pure, as ConditionalDistribution states. A value that changes
between calls belongs in an input, as sigma is in the decorator
example, and not in a global. A function that does not compile with its
unmet givens traced, such as one that converts a given to a Python number,
runs uncompiled.
Source code in probpipe/distributions/_conditional.py
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 | |
probpipe.distributions.ConditionalDistribution(given_spec, event_spec, *, label=None, _provenance=None, _annotations=None)
¶
Bases: TrackedTerm, Annotated, ABC
A probability kernel K : S → P(T): a law over its event for each given value.
Supplying a value for the inputs yields an ordinary Distribution
over what the kernel produces. A kernel always conditions on at least one
input, since binding the last one returns a Distribution, and the two
kinds are distinct: neither inherits from the other.
The kernel stores one ConditionalDistributionSpec, its spec;
given_spec and event_spec are views on it. The event
spec is read as a Distribution's is: the fields of a bare
RecordSpec are the outputs, and an OutputSpec names the output of
a whole term. The inputs and the outputs are distinct roles, so their
names are disjoint even when the two spaces coincide, as in a Markov
kernel state → next_state. Symbolic dimensions are scoped over both
sides jointly.
Users call operations rather than methods: condition_on(K, s) binds the
inputs, and sample(K, given=s), log_prob(K, y, given=s), and
mean(K, given=s) are the fused conditional calls, equal to the same
operation on condition_on(K, s) when both paths are exact. An
approximation on either path is recorded by that operation; a direct
conditional sampler may remain exact when binding builds an empirical law.
A subclass implements
_condition_on, and it may claim the conditional capabilities.
The conditional methods, such as _conditional_sample, must be pure:
their result is determined by the given values and the key or the event
they take. A joint that draws or scores the kernel at many given values
compiles the method, vectorized over those values, and keeps the compiled
program for later calls with the same constants and input shapes. A call
that reuses the program computes with the values that the globals the
method reads had when the program was compiled. A call that compiles a new
program, or that runs uncompiled, reads their current values. A Python side
effect of the method, such as a warning, happens when a program is
compiled. A family skips its checks of a traced parameter value, such as
that mixture weights are nonnegative, so inside the program an invalid
parameter computed from an unmet given or from a constant of the method
gives draws or densities such as nan rather than an error.
str(K) returns the kernel's notation, its label followed by its
signature, as glm(y | beta), and the repr reads as a call of the
constructor, with label= where a caller gave a label other than the
default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
given_spec
|
InputSpec, Mapping, RecordSpec, or OutputSpec
|
The named inputs the kernel conditions on, at least one; the keys are Python identifiers. |
required |
event_spec
|
OutputSpec or RecordSpec
|
The output spec of one produced draw, completed as above. |
required |
label
|
str
|
The kernel's label, a non-empty string, |
None
|
_provenance
|
Provenance
|
The provenance of the kernel that a reconstruction rebuilds. By default the
provenance stays unset until |
None
|
_annotations
|
Mapping[str, Any]
|
The annotations of the kernel that a reconstruction rebuilds, copied into
the kernel's own store. By default |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is not a non-empty string, given_spec is not a mapping of
term specs, or event_spec is neither an |
ValueError
|
If given_spec has no inputs, event_spec leaves its type unspecified, or an input shares a name with an output. |
Source code in probpipe/distributions/_conditional.py
raw
property
¶
This kernel detached from the workflow, under its label and specs.
A kernel is represented by itself, so its raw form is a copy that shares its representation and carries no provenance, no annotations, and no reference to a batch it was an element of.
Every read returns the same copy, which refuses provenance, since every
reader shares it. with_label gives a copy of it that can carry
provenance.
spec
property
¶
The kernel's term spec, the one stored source of its input and event specs.
given_spec
property
¶
The named inputs the kernel conditions on, read from spec.
event_spec
property
¶
The output spec of one produced draw, read from spec.
notation
property
¶
The kernel's label followed by its signature, as glm(y | beta), which str() returns.
The signature lists the event outputs in declaration order, then
| and every input in declaration order, then ; and the
paths the kernel holds fixed at given values when it holds any, as
glm(y | sigma; beta). Outputs, inputs, and paths are each joined by
", ". A product without a label reads factor by factor, as
lik(y | beta)·prior(beta | tau). The notation is a rendering of the
kernel's expression, made each time it is shown, which shows at most
the current config.notation.max_depth nested levels. No operation
reads the notation.
with_dim_sizes(**sizes)
¶
Bind named symbolic dimensions on both sides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**sizes
|
int
|
Sizes for free dimensions of either side. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A copy of the same class and label with the sizes substituted on both sides; the original is unchanged. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a name is not a free dimension of either side, or a size is negative. |
TypeError
|
If a size is not an integer. |
Source code in probpipe/distributions/_conditional.py
with_dim_names(**names)
¶
Rename symbolic dimensions on both sides, simultaneously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**names
|
str
|
New names keyed by old; names that are not free are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A copy of the same class and label with the dimensions renamed on both sides; the original is unchanged. |
Source code in probpipe/distributions/_conditional.py
rename(renames=None, /, **keyword_renames)
¶
Rename or move inputs and event paths, old -> new.
A key that starts with an input's name addresses the given side, and
one that starts with an output's name the event side, which behaves as
Distribution.rename. On the given side a target is the
node's new exact path, so it may split or group inputs, since a kernel has
no signature that fixes its top level: {"a": "theta/a"} moves the
input a into a structured input theta, and {"theta/a": "a"}
moves the field back out as an input. A node renamed within its parent
keeps its position, a moved node is appended to its new parent, and a
structured input that the moves empty dissolves. The kernel is unchanged:
the result translates a given value to this kernel's inputs before
binding it, and renames what the binding returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
renames
|
Mapping[str, str]
|
New names or paths keyed by the exact paths of the nodes they rename. |
None
|
**keyword_renames
|
str
|
Further renames, keyed by paths that are identifiers. |
{}
|
Returns:
| Type | Description |
|---|---|
ConditionalDistribution
|
The renamed kernel under the same label; the original is unchanged. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a key is neither a path of the given side nor an event path. |
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, a node is renamed twice, no renames are given, a target lies inside its own node or overlaps another, two nodes land on one path, an input name is not an identifier, or the renamed sides share a name. |
NotImplementedError
|
If this kernel is factored, since a joint renames through its factors. |
Source code in probpipe/distributions/_conditional.py
__mul__(other)
¶
Refuse * between distributions. Use & to merge them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If other is a distribution or a conditional distribution. |
Source code in probpipe/distributions/_conditional.py
__bool__()
¶
Refuse a truth value, so a and b raises. Use a & b to merge.
Raises:
| Type | Description |
|---|---|
TypeError
|
Always: a distribution has no truth value. |
__and__(other)
¶
The joint of this kernel and other, merged conditional-first.
This kernel may condition on what other produces. The result is a
FactoredDistribution when other meets every input, and a
FactoredConditionalDistribution over the unmet inputs otherwise.
Its provenance records the step & with this kernel and other as
its parents, in that order; see Distribution.__and__.
Source code in probpipe/distributions/_conditional.py
__str__()
¶
__repr__()
¶
A call of the kernel's public constructor, followed by the paths it holds fixed.
The output's name, the family parameters, and the inputs come first,
as given=('mu',), then label= and event_spec= where they
differ from the constructor's defaults, and the inputs that conditioning
bound follow as fixed=(...), as for a law.
Source code in probpipe/distributions/_conditional.py
probpipe.distributions.ConditionalNumericDistribution(given_spec, event_spec, *, label=None, _provenance=None, _annotations=None)
¶
Bases: ConditionalDistribution
The marker of a kernel whose event side is numeric.
Every K(s, ·) is then a NumericDistribution. Membership is read from
the event spec, and a class that inherits the marker claims it for
every instance, which construction checks. The marker adds no operations.
Source code in probpipe/distributions/_conditional.py
probpipe.distributions.NumericConditionalDistribution(given_spec, event_spec, *, label=None, _provenance=None, _annotations=None)
¶
Bases: ConditionalDistribution
The marker of a kernel whose given side is numeric: every input declares a numeric term.
Membership is read from the inputs, as for
ConditionalNumericDistribution.
Source code in probpipe/distributions/_conditional.py
probpipe.distributions.FullyNumericConditionalDistribution(given_spec, event_spec, *, label=None, _provenance=None, _annotations=None)
¶
Bases: NumericConditionalDistribution, ConditionalNumericDistribution
The marker of a kernel whose given and event sides are both numeric.
Source code in probpipe/distributions/_conditional.py
probpipe.distributions.ConditionalDistributionBatch(elements, /, level_names, *, label=None, element=None, axes_per_level=None, provenance=None)
¶
Bases: _ObjectBatch[ConditionalDistribution]
N separate conditional distributions along batch axes.
The elements share one input spec and one event spec. It is
the batch form of ConditionalDistributionSpec-valued terms. As for
DistributionBatch, batch[i] is a view of the stored kernel under
the label derived from the position, with provenance recording the batch and
the stored kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elements
|
numpy.ndarray or iterable of ConditionalDistribution
|
The kernels, 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. Defaults to a list of its first eight kernels in
row-major order over every batch axis, each in its notation, followed
by |
None
|
element
|
ConditionalDistributionSpec
|
The spec every element satisfies. Defaults to the first element's spec. |
None
|
axes_per_level
|
int or sequence of int
|
How many axes each level holds, outermost first (a single int is one level's count). |
None
|
provenance
|
Provenance
|
How this batch was produced. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If element is not a |
ValueError
|
If elements is empty and element is omitted, or the axes and level names disagree as for every batch. |
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/distributions/_batches.py
Factored distributions¶
A & B merges two laws into a factored joint.
probpipe.distributions.FactoredDistribution(factors, *, label=None, _scope=None, _output_name=None)
¶
Bases: Distribution, SupportsFactors
A joint distribution built from an ordered list of factors, every given met.
The factors are Distributions and ConditionalDistributions in
conditional-first order: a factor may condition on outputs that factors
to its right produce. The joint's event spec is the positional form over
the record of every factor's outputs in factor order, each factor's own
order kept, and extraction and reconstruction keep each factor's form. Each output
is produced by exactly one factor, while factor labels may repeat. A
packaged joint, which a rename that gathers outputs builds, declares
that record as a whole term under one output, and it is one factor of a
joint it enters.
Sampling and the log-density capabilities are the intersection of the factors'. The moment capabilities are decided at construction: an edge-free joint has a moment exactly when every factor does, and a dependent joint has none. The marginal is resolved per path, and its guard reports whether the marginal at a path is exact. Constructing the class itself gives the most specific registered refinement whose predicate the factors satisfy, as a family registers its factored class.
A draw is a mapping from each output to its raw value, in canonical factor order, and so is each event-typed moment. Sampling is ancestral: the factors draw from right to left, each conditional factor at the outputs it names. Scoring sums the factors' densities, each at its own event reconstructed from the outputs.
A joint constructed by this class is labeled, so its notation is
its label followed by its signature, as model(y, mu). A joint that
& or the joint operation builds is unlabeled, and its notation joins
its factors' notations with ·, as lik(y | mu)·prior(mu), until
with_label gives it a label. A law built from a joint, such as a copy,
a packaged sub-joint, or a marginal that reduces a factor to part of its
event, is labeled when the joint is. A marginal over the whole events of
several factors is a product without a label, as a(a)·b(b), and a
product that a function returns takes the function's output label. An
unlabeled product that holds paths fixed reads as its grouped label
followed by its signature, as (lik·prior)(mu; y).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factors
|
Sequence[Distribution | ConditionalDistribution]
|
The factors, in conditional-first order. |
required |
label
|
str
|
The joint's display alias. Defaults to the product of its factors' descriptions. |
None
|
_scope
|
Mapping[str, int]
|
The size of each dimension bound in the joint that a transform rebuilds, keyed by its name, which the factor graph starts from. |
None
|
_output_name
|
str
|
The name of the output under which a packaged joint declares its record as a whole term. By default the joint's outputs are the record's fields. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If a factor is neither distribution kind, or its draws are distributions or batches, which have no outputs to merge by name. |
ValueError
|
If there are no factors, an output is produced twice, a factor
conditions on an output a factor to its left produces, matched specs
do not unify, or a given is left unmet, which makes the joint a
|
Source code in probpipe/distributions/_factored.py
factors
property
¶
The factors, in conditional-first order.
with_dim_sizes(**sizes)
¶
Bind named symbolic dimensions in every factor that declares them.
The result is this joint with its dimensions bound, so a lift draws it together with this joint (V.5).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**sizes
|
int
|
Sizes for free dimensions of the joint. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The joint of the bound factors, under the same label. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a name is not a free dimension of the joint. |
Source code in probpipe/distributions/_factored.py
with_dim_names(**names)
¶
Rename symbolic dimensions in every factor, simultaneously.
The result is this joint under the new dimension names, so a lift draws it together with this joint (V.5).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**names
|
str
|
New names keyed by old; names that are not free are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The joint of the renamed factors, under the same label. |
Source code in probpipe/distributions/_factored.py
probpipe.distributions.FactoredNumericDistribution(factors, *, label=None, _scope=None, _output_name=None)
¶
Bases: FactoredDistribution
The marker of an unconditional joint whose event is numeric.
Membership is read from the event spec, as for NumericDistribution, and
a class that inherits the marker claims it for every instance, which
construction checks.
Source code in probpipe/distributions/_factored.py
probpipe.distributions.FactoredConditionalDistribution(factors, *, label=None, _scope=None, _output_name=None)
¶
Bases: ConditionalDistribution, SupportsFactors
A joint conditional distribution: factors that leave some givens unmet.
Its given_spec is exactly the unmet givens, same-named ones unified into
one input, and its event spec is read as for
FactoredDistribution. Conditioning on every given yields a
FactoredDistribution, and conditioning on some returns a smaller
FactoredConditionalDistribution.
Each conditional capability is its unconditional counterpart's on
FactoredDistribution, with every unmet given set by the given
of the call, and each factor is called through its own capability at that
value.
The joint is labeled or unlabeled as FactoredDistribution states,
so an unlabeled one reads factor by factor, as lik(y | mu)·prior(mu | tau),
and a labeled one by its label, as model(y, mu | tau).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factors
|
Sequence[Distribution | ConditionalDistribution]
|
The factors, in conditional-first order. |
required |
label
|
str
|
The joint's display alias. Defaults to the product of its factors' descriptions. |
None
|
_scope
|
Mapping[str, int]
|
The size of each dimension bound in the joint that a transform rebuilds, keyed by its name, which the factor graph starts from. |
None
|
_output_name
|
str
|
The name of the output under which a packaged joint declares its record as a whole term. By default the joint's outputs are the record's fields. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If a factor is neither distribution kind, or its draws are distributions or batches, which have no outputs to merge by name. |
ValueError
|
If the factors break a merge rule, as for
|
Source code in probpipe/distributions/_factored.py
factors
property
¶
The factors, in conditional-first order.
with_dim_sizes(**sizes)
¶
Bind named symbolic dimensions in every factor that declares them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**sizes
|
int
|
Sizes for free dimensions of either side. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The joint of the bound factors, under the same label. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a name is not a free dimension of the joint. |
Source code in probpipe/distributions/_factored.py
with_dim_names(**names)
¶
Rename symbolic dimensions in every factor, simultaneously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**names
|
str
|
New names keyed by old; names that are not free are ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
The joint of the renamed factors, under the same label. |
Source code in probpipe/distributions/_factored.py
probpipe.distributions.FactoredConditionalNumericDistribution(factors, *, label=None, _scope=None, _output_name=None)
¶
Bases: FactoredConditionalDistribution
The marker of a conditional joint whose event is numeric, read from its event spec.
Source code in probpipe/distributions/_factored.py
probpipe.distributions.FactoredNumericConditionalDistribution(factors, *, label=None, _scope=None, _output_name=None)
¶
Bases: FactoredConditionalDistribution
The marker of a conditional joint whose inputs are numeric, by its input spec.
Source code in probpipe/distributions/_factored.py
probpipe.distributions.FactoredFullyNumericConditionalDistribution(factors, *, label=None, _scope=None, _output_name=None)
¶
Bases: FactoredNumericConditionalDistribution, FactoredConditionalNumericDistribution
The marker of a conditional joint whose given and event sides are both numeric.
Source code in probpipe/distributions/_factored.py
Capabilities¶
A capability is a protocol that names one implementation method, such as _sample for SupportsSampling.
A class claims a capability by defining that method, and it claims a conditioning capability by inheriting it.
SupportsSampling
¶
Bases: Protocol
A distribution that draws via _sample(key, sample_shape).
sample_shape=() returns one draw in its raw form, and a non-empty shape
prepends independent-draw axes to it: an array for an array-drawing law, a
record of stacked columns for a record-drawing one. The sample
operation names the axes it adds, since a law cannot know what a caller's
sample_shape means.
SupportsLogProb
¶
Bases: SupportsUnnormalizedLogProb, Protocol
A distribution with the normalized log-density _log_prob(value).
It refines SupportsUnnormalizedLogProb, so the unnormalized
density defaults to the normalized one.
SupportsUnnormalizedLogProb
¶
Bases: Protocol
A distribution with a log-density up to an additive constant.
_unnormalized_log_prob(value) scores one draw, or a batch of draws
whose leading axes the result keeps.
SupportsMean
¶
Bases: Protocol
A distribution with an exact mean, _mean(), a value shaped like one draw.
A random function's mean is its mean function, and a random measure's is the marginalized law.
SupportsVariance
¶
Bases: Protocol
A distribution with an exact variance, _variance(), a value shaped like one draw.
SupportsCovariance
¶
Bases: Protocol
A numeric distribution with an exact covariance, _cov().
The result is a (d, d) linear operator over the flattened draw, whose
size is d.
SupportsQuantile
¶
Bases: Protocol
A numeric distribution with quantiles, _quantile(q), per coordinate at each level.
The result is the event's raw form with the level axes leading in each
leaf: an array of shape (*q.shape, *event_shape) for an array event,
and the nested mapping of such arrays for a record event. The quantile
operation wraps it: one level as a value of the event's kind, and several
levels as the matching batch on a level of their own.
SupportsExpectation
¶
Bases: Protocol
A distribution with the exact expectation 𝔼[f(X)] of an arbitrary f.
_expectation(f) integrates any function exactly, which in practice
means finite support. Its argument is an opaque callable that no guard can
inspect, so a law that is exact only for special maps does not claim the
capability; the expectation operation estimates such a law's
expectation through a registered method instead.
f receives each value in its raw form, so a record value is the nested
mapping of its raw leaves. The order of that mapping's keys carries no
meaning, since jax.vmap sorts them, and the expectation operation
presents the value to the integrand as a Record in the declared order.
SupportsRandomLogProb
¶
Bases: Protocol
A random measure with a random normalized log-density, _random_log_prob().
It returns the law of x ↦ log D(x) with D ~ M, as
SupportsRandomUnnormalizedLogProb does for the unnormalized one.
SupportsRandomUnnormalizedLogProb
¶
Bases: Protocol
A random measure with a random unnormalized log-density.
For a random measure M, _random_unnormalized_log_prob() returns the
law of x ↦ log D̃(x) with D̃ the unnormalized density of a draw
D ~ M, itself a random function.
SupportsExactConditioning
¶
Bases: ABC
A distribution whose _condition_on returns the conditional law.
Inherit this to claim exact conditioning, such as a conjugate update or
reweighting an empirical joint; condition_on prefers it over the
inference registry and keeps it when the caller asks for exactness. The
capability is claimed by inheriting rather than by defining
_condition_on: exactness is a claim about the result, which no
structural check can read, and two protocols declaring the same method
would match the same classes.
SupportsApproximateConditioning
¶
Bases: ABC
A distribution whose _condition_on returns a stand-in for the conditional law.
Inherit this to claim a built-in conditioning path that does not return
the conditional law itself, such as an amortized posterior that runs one
forward pass. condition_on prefers it over the inference registry and
excludes it when the caller asks for exactness. A model whose conditioning
requires MCMC or variational inference claims neither capability, so the
inference registry selects an algorithm for it.
probpipe.distributions.SupportsMarginals
¶
Bases: Protocol
A distribution that returns the standalone marginal of a field or field group.
_marginal(path) returns a standalone Distribution over the node at
path, an event path of this law, with no reference back to it. One path,
a str, gives the node whole under an output named by the path's last
name, and a path that names a group gives the group of fields under it. A
tuple of paths, which names at least one path, no path twice, and no path
inside another, gives a law over the record that keeps each node at its own
path, in this law's canonical order whatever the order of the tuple. The
marginal is labeled as the marginal operation labels it, so a law
without factors gives its marginals its own label. Support may
depend on the path, so a class whose marginal is exact only at some paths
defines the guard _marginal_guard(path).
A class may define the companion _marginal_capabilities(path), which
returns the capabilities its exact marginal at path claims, read from
its declarations without building the marginal; _marginal_claims
reads it. The marginals of a law that defines none claim what the law
claims itself.
probpipe.distributions.SupportsFactors
¶
Bases: Protocol
A distribution built from an ordered list of sub-distributions, its factors.
Each factor is a Distribution or a ConditionalDistribution. The
dependence graph is derived by matching each factor's inputs against
the outputs the factors to its right produce, so it is not stored.
Capabilities of a conditional distribution¶
Each capability of a conditional distribution takes the given value given before the arguments of its unconditional counterpart.
probpipe.distributions.SupportsConditionalSampling
¶
Bases: Protocol
A kernel that draws from K(given, ·), the twin of SupportsSampling.
probpipe.distributions.SupportsConditionalLogProb
¶
Bases: SupportsConditionalUnnormalizedLogProb, Protocol
A kernel with the normalized log-density of K(given, ·).
It refines SupportsConditionalUnnormalizedLogProb, as
SupportsLogProb refines its unnormalized counterpart, so the
unnormalized density defaults to the normalized one.
probpipe.distributions.SupportsConditionalUnnormalizedLogProb
¶
Bases: Protocol
A kernel with an unnormalized log-density of K(given, ·).
probpipe.distributions.SupportsConditionalMean
¶
Bases: Protocol
A kernel with the mean of K(given, ·), a value shaped like one draw.
probpipe.distributions.SupportsConditionalVariance
¶
Bases: Protocol
A kernel with the variance of K(given, ·), a value shaped like one draw.
probpipe.distributions.SupportsConditionalCovariance
¶
Bases: Protocol
A kernel with the covariance of K(given, ·), a (d, d) operator.
probpipe.distributions.SupportsConditionalQuantile
¶
Bases: Protocol
A numeric kernel with the quantiles of K(given, ·) at the levels q.
probpipe.distributions.SupportsConditionalExpectation
¶
Bases: Protocol
A kernel with the exact expectation 𝔼[f(Y)] for Y ~ K(given, ·).
probpipe.distributions.SupportsConditionalRandomLogProb
¶
Bases: Protocol
Like SupportsConditionalRandomUnnormalizedLogProb, with the normalized density.
probpipe.distributions.SupportsConditionalRandomUnnormalizedLogProb
¶
Bases: Protocol
A random-measure kernel: the law of x ↦ log D̃(x) with D ~ K(given, ·).
probpipe.distributions.SupportsConditionalMarginals
¶
Bases: Protocol
A kernel with the standalone marginal of K(given, ·) at an event path.
The path argument follows SupportsMarginals: one path, or a tuple
of paths that keeps each node at its own path.
Continuous families¶
TFPDistribution adapts a TensorFlow Probability distribution, and each family of this section and the next two is a subclass of it.
TFPDistribution(output_name, backend_dist, *, label=None, event_spec=None)
¶
Bases: NumericDistribution, SupportsSampling, SupportsLogProb
The law of one array, realized by a wrapped backend distribution.
The adapter samples through the backend and scores with its normalized
log-density. A family claims the further capabilities its backend
computes by listing them in _backend_capabilities: the mean and the
variance, shaped like one draw; the covariance of the flattened draw as a
linear operator; and the quantiles of each coordinate. The adapter gives
the family the method realizing each, unless the family defines its own.
One draw is the backend event's array, with its shape and dtype and the
family's support, declared as a whole term under output_name, so every
instance is a NumericDistribution. A family's label
defaults to its class name, as Normal, and the adapter's to the name of
the backend's class. A backend whose parameters have axes beyond one law's
is reinterpreted as one law whose leading event axes are those axes, over
independent coordinates or rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
backend_dist
|
Distribution
|
The wrapped backend distribution, which a family's constructor builds from its parameters. |
required |
label
|
str
|
The law's label. It defaults to the family's class name, and for the
adapter itself to the name of the backend's class, as |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw and which the adapter completes with the backend event's array. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string,
backend_dist is not a backend distribution, or event_spec is not an
|
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Notes
A family pickles and copies by rebuilding from the arguments its constructor was called with, in the form it was built in, and then restoring the state assigned since, such as a new label or provenance. The backend is rebuilt rather than copied, since some backends, such as the one reinterpreting independent coordinates, neither pickle nor deep-copy.
Source code in probpipe/families/_backend.py
raw
property
¶
The wrapped backend distribution.
__init_subclass__(**kwargs)
¶
Give a family the method realizing each capability its table lists.
A method the family implements, in its body or through a base it
inherits, is kept. A family's own constructor is wrapped to record the
arguments it is called with, which __reduce__ rebuilds the
family from.
Source code in probpipe/families/_backend.py
__reduce__()
¶
Rebuild from the recorded constructor arguments, then restore the other state.
Every attribute but the backend and the recorded arguments is restored, so a label or provenance assigned after construction is kept.
Source code in probpipe/families/_backend.py
Normal(output_name, loc, scale, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Univariate normal (Gaussian) distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
loc
|
array - like
|
Mean of the distribution. |
required |
scale
|
array - like
|
Standard deviation (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Beta(output_name, alpha, beta, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Beta distribution on [0, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
alpha
|
array - like
|
First concentration parameter (> 0). |
required |
beta
|
array - like
|
Second concentration parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Gamma(output_name, concentration, rate, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Gamma distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
concentration
|
array - like
|
Shape parameter (> 0). |
required |
rate
|
array - like
|
Rate (inverse scale) parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
InverseGamma(output_name, concentration, scale, *, label=None, event_spec=None)
¶
Bases: _TailBoundedMoments, TFPDistribution
Inverse-gamma distribution.
The mean is finite for a concentration above one and inf at most one.
The variance is finite above two, inf between one and two, and
undefined at most one, where it raises MathematicalDomainError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
concentration
|
array - like
|
Shape parameter (> 0). |
required |
scale
|
array - like
|
Scale parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Exponential(output_name, rate, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Exponential distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
rate
|
array - like
|
Rate parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
LogNormal(output_name, loc, scale, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Log-normal distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
loc
|
array - like
|
Mean of the underlying normal distribution. |
required |
scale
|
array - like
|
Standard deviation of the underlying normal distribution (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
StudentT(output_name, df, loc, scale, *, label=None, event_spec=None)
¶
Bases: _TailBoundedMoments, TFPDistribution
Student's t-distribution.
The mean is the location for degrees of freedom above one and undefined at
most one, where it raises MathematicalDomainError. The variance is
finite above two, inf between one and two, and undefined at most one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
df
|
array - like
|
Degrees of freedom (> 0). |
required |
loc
|
array - like
|
Location parameter. |
required |
scale
|
array - like
|
Scale parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Uniform(output_name, low, high, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Uniform distribution on [low, high].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
low
|
array - like
|
Lower bound. |
required |
high
|
array - like
|
Upper bound (> low). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Cauchy(output_name, loc, scale, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Cauchy distribution.
Its mean, variance, and covariance do not exist, and each raises
MathematicalDomainError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
loc
|
array - like
|
Location parameter. |
required |
scale
|
array - like
|
Scale parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Laplace(output_name, loc, scale, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Laplace distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
loc
|
array - like
|
Location parameter. |
required |
scale
|
array - like
|
Scale parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
HalfNormal(output_name, scale, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Half-normal distribution (support on [0, inf)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
scale
|
array - like
|
Scale parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
HalfCauchy(output_name, loc, scale, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Half-Cauchy distribution (support on [loc, inf)).
Its mean is inf, and its variance and covariance are undefined, since
the mean is infinite, so each raises MathematicalDomainError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
loc
|
array - like
|
Location parameter. |
required |
scale
|
array - like
|
Scale parameter (> 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Pareto(output_name, concentration, scale, *, label=None, event_spec=None)
¶
Bases: _TailBoundedMoments, TFPDistribution
Pareto distribution.
The mean is finite for a concentration above one and inf at most one.
The variance is finite above two, inf between one and two, and
undefined at most one, where it raises MathematicalDomainError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
concentration
|
array - like
|
Tail index (shape parameter, > 0). |
required |
scale
|
array - like
|
Minimum value (scale parameter, > 0). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
TruncatedNormal(output_name, loc, scale, low, high, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Truncated normal distribution on [low, high].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
loc
|
array - like
|
Mean of the underlying normal distribution. |
required |
scale
|
array - like
|
Standard deviation of the underlying normal distribution (> 0). |
required |
low
|
array - like
|
Lower truncation bound. |
required |
high
|
array - like
|
Upper truncation bound (> low). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_continuous.py
Discrete families¶
Bernoulli(output_name, *, probs=None, logits=None, label=None, event_spec=None)
¶
Bases: TFPDistribution
Bernoulli distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
probs
|
array - like
|
Probability of a 1 outcome. Exactly one of probs or logits must be provided. |
None
|
logits
|
array - like
|
Log-odds of a 1 outcome. |
None
|
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If not exactly one of probs and logits is given, or event_spec declares a type that one draw does not conform to. |
Source code in probpipe/families/_discrete.py
Binomial(output_name, total_count, *, probs=None, logits=None, label=None, event_spec=None)
¶
Bases: TFPDistribution
Binomial distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
total_count
|
array - like
|
Number of trials. |
required |
probs
|
array - like
|
Probability of success per trial. Exactly one of probs or logits must be provided. |
None
|
logits
|
array - like
|
Log-odds of success per trial. |
None
|
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If not exactly one of probs and logits is given, or event_spec declares a type that one draw does not conform to. |
Source code in probpipe/families/_discrete.py
Poisson(output_name, rate, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Poisson distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
rate
|
array - like
|
Rate parameter (must be positive). |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_discrete.py
Categorical(output_name, *, probs=None, logits=None, label=None, event_spec=None)
¶
Bases: TFPDistribution
Categorical distribution over k classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
probs
|
array - like
|
Probabilities for each category. Exactly one of probs or logits must be provided. |
None
|
logits
|
array - like
|
Unnormalized log-probabilities for each category. |
None
|
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If not exactly one of probs and logits is given, or event_spec declares a type that one draw does not conform to. |
Source code in probpipe/families/_discrete.py
NegativeBinomial(output_name, total_count, *, probs=None, logits=None, label=None, event_spec=None)
¶
Bases: TFPDistribution
Negative binomial distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
total_count
|
array - like
|
Number of successes before stopping. |
required |
probs
|
array - like
|
Probability of success per trial. Exactly one of probs or logits must be provided. |
None
|
logits
|
array - like
|
Log-odds of success per trial. |
None
|
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If not exactly one of probs and logits is given, or event_spec declares a type that one draw does not conform to. |
Source code in probpipe/families/_discrete.py
Multivariate families¶
MultivariateNormal(output_name, loc, scale_tril=None, *, cov=None, label=None, event_spec=None)
¶
Bases: TFPDistribution
Multivariate normal (Gaussian) distribution.
Its covariance keeps the structure it was given: a LinOp as it is, a
dense matrix as a DenseLinOp, and a Cholesky factor as a
CholeskyLinOp over it. The variance is the covariance's diagonal, and
the quantile of each coordinate is that of its normal marginal,
loc + sqrt(cov_ii) Φ⁻¹(q).
A singular covariance. A covariance that is positive semidefinite but
singular has no Cholesky factor, so the family draws through a
rank-tolerant one: the symmetric eigendecomposition with its eigenvalues
clipped at zero, reduced to a lower-triangular factor. The law is then
concentrated on an affine subspace and has no density with respect to
Lebesgue measure, so its log-density raises MathematicalDomainError. A
covariance whose Cholesky factorization fails is treated as singular. A
traced covariance chooses its factor when the computation runs, and its
log-density is NaN where the covariance is singular.
Independent rows. Parameters with axes beyond one law's, a loc of
shape (n, d) or a covariance or factor of shape (n, d, d), give one
law over an (n, d) array of n independent rows. Its density sums the
rows' densities, its mean and variance have the shape (n, d), its
covariance over the flattened draw is the block-diagonal matrix of the
rows' covariances, and its quantiles are per coordinate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
loc
|
array-like, shape ``(..., d)``
|
Mean vector, or one per row. |
required |
scale_tril
|
array-like, shape ``(..., d, d)``
|
Lower-triangular Cholesky factor of the covariance, or one per row. Exactly one of scale_tril or cov must be provided. |
None
|
cov
|
LinOp or array-like, shape ``(..., d, d)``
|
Covariance, as an operator or a matrix, or one matrix per row, factored for the backend. |
None
|
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If not exactly one of scale_tril and cov is given, the trailing axes
of cov are not |
Source code in probpipe/families/_multivariate.py
scale_tril
property
¶
A lower-triangular factor L of the covariance, L Lᵀ = cov.
It is the Cholesky factor when the covariance is positive definite, and the rank-tolerant factor when it is singular.
cov
property
¶
The covariance matrix of a row: the one given, or L Lᵀ for a given factor L.
dim
property
¶
The length d of a row.
Dirichlet(output_name, concentration, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Dirichlet distribution over the probability simplex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
concentration
|
array-like, shape ``(..., k)``
|
Positive concentration (alpha) parameters, or one vector per row. |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If concentration is a scalar, or event_spec declares a type that one draw does not conform to. |
Source code in probpipe/families/_multivariate.py
Multinomial(output_name, total_count, probs=None, logits=None, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Multinomial distribution over count vectors.
Exactly one of probs or logits must be provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
total_count
|
int or array - like
|
Number of trials, or one per row. |
required |
probs
|
array-like, shape ``(..., k)``
|
Event probabilities (need not be normalised), or one vector per row. |
None
|
logits
|
array-like, shape ``(..., k)``
|
Log-odds of each event, or one vector per row. |
None
|
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If not exactly one of probs and logits is given, or event_spec declares a type that one draw does not conform to. |
Source code in probpipe/families/_multivariate.py
Wishart(output_name, df, scale_tril=None, *, scale=None, label=None, event_spec=None)
¶
Bases: TFPDistribution
Wishart distribution over positive-definite matrices.
Exactly one of scale_tril or scale must be provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
df
|
float or array - like
|
Degrees of freedom (must be >= dimension), or one per row. |
required |
scale_tril
|
array-like, shape ``(..., d, d)``
|
Lower-triangular Cholesky factor of the scale matrix, or one per row. |
None
|
scale
|
array-like, shape ``(..., d, d)``
|
Full scale matrix (Cholesky-decomposed internally), or one per row. |
None
|
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If not exactly one of scale_tril and scale is given, or event_spec declares a type that one draw does not conform to. |
Source code in probpipe/families/_multivariate.py
scale
property
¶
Full scale matrix (computed from Cholesky factor).
VonMisesFisher(output_name, mean_direction, concentration, *, label=None, event_spec=None)
¶
Bases: TFPDistribution
Von Mises-Fisher distribution on the unit hypersphere.
Its variance is the diagonal of its covariance, which the backend computes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
mean_direction
|
array-like, shape ``(..., d)``
|
Unit vector giving the mean direction, or one per row. |
required |
concentration
|
float or array - like
|
Scalar concentration parameter (kappa >= 0), or one per row. |
required |
label
|
str
|
The law's label, the family's class name by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw
and which the family completes, as
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If output_name is not a string, label is not a non-empty string, or
event_spec is not an |
ValueError
|
If output_name is not a valid output name, or event_spec names another output or declares a type that one draw does not conform to. |
Source code in probpipe/families/_multivariate.py
Resampling families¶
BootstrapReplicateDistribution(output_name, source, replicate_size=None, *, label=None, level=None, event_spec=None)
¶
Bases: Distribution, SupportsSampling
The law of one bootstrap replicate: replicate_size iid draws of a source.
A draw is one replicate, the source's draws in the event's batch form on one level. The source is any law that samples: an empirical source is resampled by weight, which is the nonparametric bootstrap, and a fitted law is redrawn, which is the parametric bootstrap.
The event spec. One draw is a batch of the source's event term on the replicate's level, so a replicate keeps the source's term kind. The event spec is the law's own, derived from the source and the replicate size, under output_name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
source
|
Distribution
|
The law the replicate draws from, which implements |
required |
replicate_size
|
int
|
The number of draws in one replicate. It defaults to the atom count of an empirical source and is required otherwise. |
None
|
label
|
str
|
The law's label, |
None
|
level
|
str
|
The level a replicate's draws lie on. It defaults to the source's atom level when the source is an empirical law with exactly one, and otherwise to the name of the source's output when the source has one, as a whole-term event does. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If source is not a law that samples, output_name or level is not a
string, label is not a non-empty string, replicate_size is not an
integer, or event_spec is not an |
ValueError
|
If replicate_size is not positive or is omitted for a source without atoms, level is omitted for a source with several outputs or is not a valid level name, event_spec names another output, or it declares a type that does not unify with the replicate's. |
Examples:
>>> import jax.numpy as jnp
>>> data = EmpiricalDistribution(jnp.array([1.0, 2.0, 4.0]), output_name="y")
>>> replicate = BootstrapReplicateDistribution("boot", data)
>>> replicate.replicate_size
3
>>> replicate.event_spec.term_spec.level_names
('y',)
Source code in probpipe/families/_resampling.py
BootstrapDistribution(output_name, source, replicate_size=None, *, label=None, level=None, event_spec=None)
¶
Bases: RandomMeasure, SupportsSampling, SupportsMean
The bootstrap random measure: a draw is the empirical measure of one replicate.
A draw is an EmpiricalDistribution whose atoms are one replicate,
replicate_size iid draws of the source on one level, with uniform
weights. The bootstrap distribution of a statistic is
pushforward(B, stat) over the measure B, whose draws the statistic
receives as laws, or pushforward(R, stat) over the replicate law
BootstrapReplicateDistribution for a statistic that reads a
dataset.
The event spec. One draw is declared as a law carrying the source's complete event spec, so its outputs and their form are the source's. The measure's own event spec is distinct: a whole term under output_name.
Capabilities. The measure samples, and its mean, the marginalized law
𝔼[D](A) of a draw D, is the source itself, since each atom of a
replicate is a draw of the source. A draw has no density, so the measure
claims no random log-density.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the measure's one output, which names its draws. |
required |
source
|
Distribution
|
The law a replicate draws from, which implements |
required |
replicate_size
|
int
|
The number of atoms of a drawn measure. It defaults to the atom count of an empirical source and is required otherwise. |
None
|
label
|
str
|
The law's label, |
None
|
level
|
str
|
The level the atoms of a drawn measure lie on, defaulting as for
|
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw. |
None
|
Raises:
| Type | Description |
|---|---|
(TypeError, ValueError)
|
As |
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> data = EmpiricalDistribution(jnp.array([1.0, 2.0, 4.0]), output_name="y")
>>> measure = BootstrapDistribution("boot", data)
>>> draw = measure._sample(jax.random.PRNGKey(0))
>>> (type(draw).__name__, draw.num_atoms, list(draw.event_spec.outputs))
('EmpiricalDistribution', 3, ['y'])
Source code in probpipe/families/_resampling.py
KDEDistribution(atoms, bandwidth=None, weights=None, kernel=GaussianKernel, *, output_name=None, label=None, event_spec=None)
¶
Bases: Distribution, SupportsSampling, SupportsLogProb, SupportsMean, SupportsVariance, SupportsCovariance
The kernel density estimate of weighted atoms under a smoothing kernel.
The law is the weighted mixture Σᵢ wᵢ h⁻ᵈ K((x − xᵢ)/h) of the kernel's
copies placed at the atoms, with the bandwidth h as their scales. The
kernel class builds the bank of copies through
SmoothingKernel.build_kernels, so the estimate reads no
kernel-specific parameter. Records enter through their flat vectors: a
NumericRecordBatch of atoms is flattened to its coordinates, and a
NumericRecord of scales matches its fields by path.
The bandwidth. A value is one scale, one per coordinate, or one per atom
and coordinate. A string names a selection rule, "scott" or
"silverman", and None selects Scott's rule. Both rules count Kish's
effective sample size, so they stay sensible under importance weights.
The event spec. Each field of record atoms is an output of the law,
and array atoms form a whole-term event under output_name. An event_spec names the
outputs, as for EmpiricalDistribution. Every leaf is declared
floating, on the real line.
Capabilities.
========================== ===================================================
capability realized by
========================== ===================================================
_sample an atom drawn by weight, then a draw from its copy
_log_prob the weighted log-sum-exp of the copies' densities
_mean the weighted mean of the atoms
_variance the atoms' weighted variance plus the mean squared
scale times the kernel's variance
_cov the atoms' weighted covariance plus that diagonal,
a DenseLinOp over the flat coordinates
========================== ===================================================
Every capability is exact for the law. A record event's draw and moments are nested mappings of raw leaves, and its density reads a record value in raw form or a batch of records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms
|
array - like or NumericRecordBatch
|
The centers of the copies, along a leading axis of atoms. |
required |
bandwidth
|
ArrayLike, NumericRecord, or str
|
The scales of the copies, or the name of a selection rule; |
None
|
weights
|
Array or Weights
|
Nonnegative weights with a positive sum, one per atom; uniform when omitted. |
None
|
kernel
|
type of SmoothingKernel
|
The smoothing kernel, |
GaussianKernel
|
output_name
|
str
|
The name of the law's one output, which names its draws, required for array atoms unless event_spec names it, and refused for record atoms. |
None
|
label
|
str
|
The law's label, |
None
|
event_spec
|
OutputSpec
|
An event spec giving the type of one draw, completed with the atoms' spec. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If atoms is neither a numeric array-like nor a |
ValueError
|
If the atoms hold none or have no leading axis, the atoms of a list or a tuple have different shapes, the weights are invalid, bandwidth names no rule or a rule selects a zero scale, the scales do not broadcast against the atoms or are not positive, or event_spec names another output or declares a type that does not unify with the atoms'. |
Examples:
>>> import jax.numpy as jnp
>>> kde = KDEDistribution(jnp.array([0.0, 1.0, 3.0]), 0.5, output_name="x")
>>> round(float(kde._mean()), 4)
1.3333
>>> round(float(kde._variance()), 4) # the atoms' variance 14/9, plus 0.5 ** 2
1.8056
Source code in probpipe/families/_resampling.py
num_atoms
property
¶
The number of atoms, one copy of the kernel placed at each.
probpipe.families.SmoothingKernel(centers, scales)
¶
Bases: ABC
A bank of mean-zero kernel copies, one placed at each center.
A smoothing kernel is a mean-zero density K over the coordinates of one
atom. The copy placed at center c with scales h has the density
x ↦ K((x − c) / h) / ∏ⱼ hⱼ, where the product runs over the coordinates.
build_kernels is the uniform constructor: it takes the centers and
the scales and returns the bank, whatever the concrete kernel, so a kernel
density estimate holds the kernel class and never reads kernel-specific
parameters. The bank draws from indexed copies with _sample and
scores a point under every copy with _log_density.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
centers
|
ArrayLike or NumericRecordBatch
|
One center per atom along the leading axis, |
required |
scales
|
ArrayLike or NumericRecord
|
The scales, broadcast against the centers: one scale, one per coordinate, or one per center and coordinate. A numeric record of scales requires record centers with the same fields, matched by leaf path. Each field's scale broadcasts over that field's coordinates, and the scales are flattened in the centers' field order. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
variance |
float
|
The variance of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the centers have no atom axis, a record of scales does not have the centers' fields, or the scales do not broadcast against the centers or are not positive. |
Source code in probpipe/families/_resampling.py
build_kernels(centers, scales)
abstractmethod
classmethod
¶
The bank of copies placed at centers with scales, one copy per center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
centers
|
ArrayLike or NumericRecordBatch
|
One center per atom along the leading axis, as for |
required |
scales
|
ArrayLike or NumericRecord
|
The scales, broadcast against the centers as for |
required |
Returns:
| Type | Description |
|---|---|
SmoothingKernel
|
An instance of this kernel class holding the placed copies. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the centers have no atom axis, a record of scales does not have the centers' fields, or the scales do not broadcast against the centers or are not positive. |
Source code in probpipe/families/_resampling.py
probpipe.families.GaussianKernel(centers, scales)
¶
Bases: SmoothingKernel
The Gaussian smoothing kernel: a standard normal density in each coordinate.
Its variance is one, so the copy with scale h is the normal law with the
center as its mean and h as its standard deviation in each coordinate.
Parameters and errors are those of SmoothingKernel.
Source code in probpipe/families/_resampling.py
build_kernels(centers, scales)
classmethod
¶
The bank of normal copies placed at centers with the standard deviations scales.
Source code in probpipe/families/_resampling.py
probpipe.families.EpanechnikovKernel(centers, scales)
¶
Bases: SmoothingKernel
The product Epanechnikov kernel: K(u) = ¾ (1 − u²) on [-1, 1] per coordinate.
Its variance is one fifth in each coordinate. A copy has compact support, so
its log-density is -inf beyond one scale from its center in any
coordinate. Parameters and errors are those of SmoothingKernel.
Source code in probpipe/families/_resampling.py
build_kernels(centers, scales)
classmethod
¶
The bank of Epanechnikov copies placed at centers with the half-widths scales.
Source code in probpipe/families/_resampling.py
Mixtures¶
probpipe.families.MixtureDistribution(components, weights, *, label=None)
¶
Bases: Distribution
A convex combination of component laws that share one event spec.
The components share one event spec, which includes the output names, the
kind, and the form, keyword or positional, while their labels may differ; a
leaf whose components declare different dtypes or supports leaves them
undeclared in the mixture's event spec. The mixture samples when every
component samples, choosing a component by the weights and then drawing
from it, and it has a normalized log-density, the weighted log-sum-exp of
the components', when every component has one. Its
moments combine entry by entry when every component provides them: the
mean is Σ wᵢ mᵢ, the variance Σ wᵢ (vᵢ + mᵢ²) − m², and the
covariance of the flat coordinates Σ wᵢ (Σᵢ + mᵢ mᵢᵀ) − m mᵀ. Each of
these capabilities carries the components' guards of the methods it calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
Sequence[Distribution]
|
The component laws, at least one, sharing one event spec. |
required |
weights
|
Array
|
One nonnegative weight per component, summing to one. |
required |
label
|
str
|
The mixture's label, |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If components is a string, a component is not a |
ValueError
|
If there is no component, two components declare different events, or the weights are not one nonnegative weight per component summing to one. |
Source code in probpipe/families/_mixture.py
Transformed distributions¶
BijectorTransformedDistribution(output_name, base, bijector, *, label=None)
¶
Bases: Distribution
The law of f(X) for X ~ base and an invertible map f with a Jacobian.
Construction checks that bijector is invertible and claims the
log-determinant of its Jacobian. Sampling pushes the base's draws through
the bijector, and the log-density at y is the base's log-density at the
preimage minus the log-determinant of the Jacobian there. A backend
bijector enters as a Function that claims the inverse and the
log-Jacobian the backend computes.
The law claims sampling when the base does and the density the base has.
It claims a moment only where the bijector gives it in closed form: when
the forward map is affine, 𝔼[f(X)] = f(𝔼[X]) and Cov(f(X)) = J
Cov(X) Jᵀ with J the map's constant Jacobian. The moment operations
estimate the others by their Monte Carlo fallback.
One draw is an array whose shape and dtype are those of the bijector's output at a draw of the base, declared as a whole term under output_name; its support is the one the bijector maps onto when that is known.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the transformed law's one output, which names its draws. |
required |
base
|
Distribution
|
The law of |
required |
bijector
|
Function
|
The invertible map |
required |
label
|
str
|
The transformed law's label, |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If base is not a |
ValueError
|
If output_name is not a valid output name. |
ResolutionError
|
If bijector does not claim |
Source code in probpipe/families/_transformed.py
probpipe.families.LinearPushforwardDistribution(output_name, base, op, *, label=None)
¶
Bases: Distribution
The law of op @ X for X ~ base, represented lazily.
The event type is op's output type, under the pushforward's own
output name. Sampling pushes the base's draws through op. The mean and
the covariance delegate exactly, 𝔼[A X] = A 𝔼[X] and Cov(A X) = A
Cov(X) Aᵀ, lazily through the operator algebra. The log-density exists
only when op is invertible, by change of variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the pushforward's one output, which names its draws. |
required |
base
|
Distribution
|
The law of |
required |
op
|
LinOp
|
The linear map. |
required |
label
|
str
|
The pushforward's label, |
None
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, until the linear evaluation rule is implemented. |
Source code in probpipe/families/_transformed.py
Gaussian joints¶
probpipe.families.FactoredMultivariateGaussian(factors, *, label=None, _scope=None, _output_name=None)
¶
Bases: FactoredNumericDistribution, SupportsExactConditioning
The factored joint whose factors are jointly Gaussian.
The class registers with the factored joints at import, so &, a joint
rebuilt by a transform, a packaged joint that a regrouping rename builds,
and a conditional joint bound at its givens construct it as the most
specific class whenever every factor is a Normal, a
MultivariateNormal, or a packaged joint of such factors; it is derived
rather than built by hand. Such factors are independent, so the joint's sampling, log-density,
moments, quantiles, and marginals are the edge-free joint's, each in closed
form, and its covariance is block diagonal over the flattened draw.
Conditioning on some of its outputs is exact: the conditional law of
the others is the joint of their factors, which the values conditioned on
leave unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factors
|
Sequence[Distribution | ConditionalDistribution]
|
The jointly Gaussian factors, in conditional-first order. |
required |
label
|
str
|
The joint's label. By default the label joins the factors' labels with
|
None
|
_scope
|
Mapping[str, int]
|
The sizes already bound in the joint's dimension scope, by dimension name, which a joint rebuilt from its factors passes on. |
None
|
_output_name
|
str
|
The one output under which a packaged joint declares its record. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If a factor is not a Gaussian law. |
ValueError
|
If the factors break a merge rule, as for
|
Source code in probpipe/families/_gaussian.py
Conditional families¶
probpipe.families.LinearGaussianConditional(output_name, A, b, cov, *, label=None)
¶
Bases: ConditionalDistribution
The linear-Gaussian kernel s ↦ N(A @ s + b, cov).
It is the conditional member of the Gaussian algebra: merged with a
Gaussian prior it yields a FactoredMultivariateGaussian, and
conditioning through it is exact. The kernel's one input is A's input,
and its event type is A's output type, under the kernel's own output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the kernel's one output, which names its draws. |
required |
A
|
LinOp
|
The linear map of the mean, whose input is the kernel's input. |
required |
b
|
Array
|
The offset of the mean, shaped like |
required |
cov
|
LinOp
|
The covariance of the event, square over |
required |
label
|
str
|
The kernel's label, |
None
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, until |
Source code in probpipe/families/_conditional.py
probpipe.families.glm_likelihood(output_name, family, link=None, *, label=None, event_spec=None, X=None, dispersion=None)
¶
The kernel of a generalized linear model, from a family, a link, and X @ beta.
The kernel's inputs are X of shape ("obs", "features"),
beta of shape ("features",), and dispersion when the family has
one, and its event is the response vector of shape ("obs",) under
output_name. Its law at a given value is family.build(output_name,
link⁻¹(X @ beta), dispersion, label=label), which carries the kernel's
label: GaussianFamily with the identity link is linear
regression, BernoulliFamily with the logit is logistic regression, and
PoissonFamily with the logarithm is Poisson regression. A value of X
or of the dispersion supplied here is fixed at construction, as
condition_on would bind it, and X binds the dimensions obs and
features; the dimensions are symbolic otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the kernel's one output, which names the response. |
required |
family
|
GLMFamily
|
The response family. |
required |
link
|
Function
|
The invertible link from the mean to the linear predictor. Defaults to the family's canonical link. |
None
|
label
|
str
|
The kernel's label, |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the response's type, passed through to the family. |
None
|
X
|
Array
|
The design matrix, of shape |
None
|
dispersion
|
ArrayLike
|
The dispersion, fixed at construction; only for a family that has one. |
None
|
Returns:
| Type | Description |
|---|---|
ConditionalDistribution
|
The GLM kernel, which claims conditional sampling, log-density, mean, variance, and covariance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If family is not a |
ResolutionError
|
If link is not invertible. |
ValueError
|
If X is not a matrix, output_name is not a valid output name, event_spec names another output, declares a type the response vector does not conform to, or a number of observations that X contradicts, or output_name is also the name of an input. |
Source code in probpipe/families/_conditional.py
probpipe.families.GLMFamily()
¶
Bases: ABC
A mean-parameterized response family of a generalized linear model.
build returns the law of conditionally independent observations,
one per entry of mean. canonical_link is the family's canonical link
g, which maps the mean invertibly to the linear predictor, and
has_dispersion declares whether build takes a dispersion, such
as a Gaussian scale. A family needs only these three members. It may also
set _support to the support of one observation, which the likelihood
declares for its response, and it may override _build_canonical to
build the law from the linear predictor of the canonical link.
Raises:
| Type | Description |
|---|---|
ResolutionError
|
At construction, if the canonical link is not invertible. |
Source code in probpipe/families/_conditional.py
build(output_name, mean, dispersion=None, *, label=None, event_spec=None)
abstractmethod
¶
The law of len(mean) conditionally independent observations with these means.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_name
|
str
|
The name of the law's one output, which names its draws. |
required |
mean
|
Array
|
One mean per observation, a vector. |
required |
dispersion
|
ArrayLike
|
The dispersion, required when the family has one and refused otherwise. |
None
|
label
|
str
|
The law's label, the class name of the law's family by default. |
None
|
event_spec
|
OutputSpec
|
An event spec naming output_name, which gives the type of one draw; the family completes it with the response vector. |
None
|
Returns:
| Type | Description |
|---|---|
Distribution
|
The law of the response vector, one entry per observation. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a dispersion is missing for a family that has one, or given to a
family that has none, or event_spec is not an |
ValueError
|
If mean is not a vector, or event_spec declares a type the response vector does not conform to. |
Source code in probpipe/families/_conditional.py
probpipe.families.GaussianFamily()
¶
Bases: GLMFamily
The Gaussian response family: independent normal observations.
The canonical link is the identity, which makes the GLM a linear regression, and the dispersion is the observation scale, the standard deviation of each observation.
Source code in probpipe/families/_conditional.py
build(output_name, mean, dispersion=None, *, label=None, event_spec=None)
¶
Independent normal observations with these means and the scale dispersion.
Parameters and errors are those of GLMFamily.build.
Source code in probpipe/families/_conditional.py
probpipe.families.BernoulliFamily()
¶
Bases: GLMFamily
The Bernoulli response family: independent binary observations.
The canonical link is the logit, which makes the GLM a logistic regression, and the family takes no dispersion. The mean of an observation is its probability of a one.
Source code in probpipe/families/_conditional.py
build(output_name, mean, dispersion=None, *, label=None, event_spec=None)
¶
Independent Bernoulli observations with the probabilities mean.
Parameters and errors are those of GLMFamily.build.
Source code in probpipe/families/_conditional.py
probpipe.families.PoissonFamily()
¶
Bases: GLMFamily
The Poisson response family: independent count observations.
The canonical link is the logarithm, which makes the GLM a Poisson regression, and the family takes no dispersion. The mean of an observation is its rate.
Source code in probpipe/families/_conditional.py
build(output_name, mean, dispersion=None, *, label=None, event_spec=None)
¶
Independent Poisson observations with the rates mean.
Parameters and errors are those of GLMFamily.build.
Source code in probpipe/families/_conditional.py
Program-defined families¶
StanModel and PyMCModel import from probpipe as well as from probpipe.families.
probpipe.families.StanModel(stan_file, *, data=None, label=None)
¶
Bases: ConditionalDistribution, SupportsConditionalUnnormalizedLogProb
The kernel from a Stan program's data-block variables to its unnormalized posterior.
The inputs are the data-block variables data leaves unbound, which the
program does not divide into sizes, covariates, and observations, and the
event is the parameter record. Each input is typed as its variable is
declared, and each parameter carries its dtype and the support its declared
constraint states; a size that names an unbound variable is the dimension of
that name on both sides. It claims SupportsConditionalUnnormalizedLogProb
alone: binding every data variable yields the unnormalized posterior, whose density
is BridgeStan's in the constrained parameterization without the Jacobian,
and condition_on normalizes it with a method such as Stan's NUTS. The
declarations are read at construction from stanc --info and the
program's text, and BridgeStan compiles the program when a density is
first evaluated. The first construction on a machine downloads BridgeStan's
source tree and its stanc compiler, as BridgeStan's first compile does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stan_file
|
str
|
The location of the |
required |
data
|
Mapping[str, Any]
|
Values of some data-block variables, bound at construction. A
construction that binds every data variable returns the posterior, a
|
None
|
label
|
str
|
The label of the kernel or of the posterior, |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
KeyError
|
If data names a variable the data block does not declare. |
ValueError
|
If stanc rejects the program, the program declares no parameters, or a declaration cannot be read. |
Source code in probpipe/families/_programs.py
probpipe.families.PyMCModel(model_fn, *, label=None)
¶
Bases: Distribution
The joint law a PyMC model-building function defines over its free variables.
The free variables are the parameters and the observed variables alike: an
argument that the function passes as an observed variable's observed
value is an event field, and an observed variable's shape is the one the
build without its data gives. Any other argument is an input, so a
model with covariates constructs the kernel over them, whose law at given
covariates is a PyMCModel. It claims sampling, which draws from the prior predictive,
and a normalized density. A model with a potential or an improper prior
claims the unnormalized density alone, since its prior predictive does not
draw from its law. Conditioning on observed values is Bayes' rule, which the
PyMC methods of the inference-method registry normalize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_fn
|
callable
|
A function returning a |
required |
label
|
str
|
The label of the law or of the kernel, |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If PyMC is not installed, or if its release is older than the floor of
the |
TypeError
|
If model_fn cannot be built with its arguments' defaults. |