Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

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

sample(key), one draw of the law at a PRNG key.

None
log_prob callable

log_prob(value), the normalized log-density of one value.

None
unnormalized_log_prob callable

unnormalized_log_prob(value), the log-density of one value up to an additive constant.

None
event_spec OutputSpec or TermSpec

The spec of one draw. An OutputSpec names its outputs, the fields of a bare RecordSpec are the outputs, and any other bare spec is a whole term under output_name.

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, ℙ by default.

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
def distribution(
    *,
    sample: Callable[[PRNGKey], Any] | None = None,
    log_prob: Callable[[Any], Array] | None = None,
    unnormalized_log_prob: Callable[[Any], Array] | None = None,
    event_spec: OutputSpec | TermSpec,
    output_name: str | None = None,
    label: str | None = None,
) -> Distribution:
    """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
    ----------
    sample : callable, optional
        ``sample(key)``, one draw of the law at a PRNG key.
    log_prob : callable, optional
        ``log_prob(value)``, the normalized log-density of one value.
    unnormalized_log_prob : callable, optional
        ``unnormalized_log_prob(value)``, the log-density of one value up to an
        additive constant.
    event_spec : OutputSpec or TermSpec
        The spec of one draw. An ``OutputSpec`` names its outputs, the fields
        of a bare ``RecordSpec`` are the outputs, and any other bare spec is a
        whole term under *output_name*.
    output_name : str, optional
        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*.
    label : str, optional
        The law's label, ``ℙ`` by default.

    Returns
    -------
    Distribution
        The law, which claims the capability of each function given.

    Raises
    ------
    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.
    """
    label = _given_label(label, DEFAULT_LABEL, owner="distribution")
    functions = {
        "sample": sample,
        "log_prob": log_prob,
        "unnormalized_log_prob": unnormalized_log_prob,
    }
    given = {name: function for name, function in functions.items() if function is not None}
    if not given:
        raise TypeError(
            f"distribution {label!r} needs at least one of sample, log_prob, or "
            f"unnormalized_log_prob"
        )
    for name, function in given.items():
        if not callable(function):
            raise TypeError(
                f"the {name} of {label!r} must be callable; got {type(function).__name__}"
            )
    if log_prob is not None and unnormalized_log_prob is not None:
        raise TypeError(f"distribution {label!r}: pass log_prob or unnormalized_log_prob, not both")
    declaration = _event_declaration(output_name, event_spec)
    sampler_traces = False
    if sample is not None:
        declaration, sampler_traces = _sampler_declaration(label, sample, declaration)
    if declaration.term_spec is None:
        raise TypeError(
            f"event_spec of {label!r} does not declare a type, and only a sample function that "
            f"traces in JAX can infer it; give the type, such as NumericArraySpec(()) for a "
            f"real scalar"
        )
    density_traces = False
    for name in ("log_prob", "unnormalized_log_prob"):
        if name in given:
            density_traces = _density_traces(label, name, given[name], declaration)
    return _FunctionLaw(
        label,
        declaration,
        sample=sample,
        log_prob=log_prob,
        unnormalized_log_prob=unnormalized_log_prob,
        sampler_traces=sampler_traces,
        density_traces=density_traces,
    )

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, ℙ by default. A subclass's constructor passes the label its caller gave, or its own default.

None
_provenance Provenance

The provenance of the law that a reconstruction rebuilds. By default the provenance stays unset until with_provenance attaches one.

None
_annotations Mapping[str, Any]

The annotations of the law that a reconstruction rebuilds, copied into the law's own store. By default annotations is None.

None

Raises:

Type Description
TypeError

If label is not a non-empty string, or event_spec is neither an OutputSpec nor a RecordSpec.

ValueError

If event_spec leaves its type unspecified.

Source code in probpipe/distributions/_distribution.py
def __init__(
    self,
    event_spec: OutputSpec | TermSpec,
    *,
    label: str | None = None,
    _provenance: Provenance | None = None,
    _annotations: Mapping[str, Any] | None = None,
):
    label = _constructor_label(self, label, DEFAULT_LABEL) if label is None else label
    _given_label(label, owner=public_class_name(type(self)))
    # ``_provenance`` and ``_annotations`` carry state a reconstruction
    # already holds and that construction cannot otherwise reach: provenance
    # is write-once, and annotations are written after construction, so a
    # rebuilt distribution would come back without either. Private, and the
    # reconstruction paths are the only callers.
    self._init_tracked(label, provenance=_provenance)
    _record_default_expression(self)
    self._init_annotations(_annotations)
    self._init_declaration(event_spec)

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 "dtype".

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
def __getattr__(self, name: str) -> Any:
    """Resolve a view of :class:`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 : str
        The attribute that ordinary lookup did not find, such as ``"dtype"``.

    Returns
    -------
    Any
        The value of the marker's view *name* for this law.

    Raises
    ------
    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.
    """
    view = _NUMERIC_VIEWS.get(name)
    if view is None:
        # Repeat ordinary lookup, so the error it met stands, a property's own
        # message included.
        return object.__getattribute__(self, name)
    if not _declares_numeric_event(self):
        raise AttributeError(
            f"{name} is only available for a distribution with a numeric event, but "
            f"{public_class_name(type(self))} {self.label!r} has a non-numeric event"
        )
    return view.__get__(self, type(self))

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
def with_label(self, label: str) -> Self:
    """Return a copy of this law under a new label.

    The copy shares the representation and records the relabeling in its
    provenance, as :meth:`TrackedTerm.with_label` states. It is this law
    under a new label, so a lift draws it together with this law (V.5).

    Parameters
    ----------
    label : str
        The new label, a non-empty string.

    Returns
    -------
    Self
        A copy of the same class under *label*; the original is unchanged.

    Raises
    ------
    TypeError
        If *label* is not a non-empty string.
    """
    return _recorded_copy(super().with_label(label), self)

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
def with_dim_sizes(self, **sizes: int) -> Self:
    """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
    ----------
    **sizes : int
        Sizes for free dimensions of the event spec.

    Returns
    -------
    Self
        A copy of the same class and label whose event spec has the sizes
        substituted; the original is unchanged.

    Raises
    ------
    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.
    """
    unbound = set(sizes) - self.event_spec.term_spec.free_dims
    if unbound:
        raise ValueError(_no_free_dims(self, unbound, self.event_spec.term_spec.free_dims))
    copy = self._with_declaration(
        self.event_spec.with_dim_sizes(**sizes), "with_dim_sizes", sizes
    )
    return _recorded_copy(copy, self)

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
def with_dim_names(self, **names: str) -> Self:
    """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
    ----------
    **names : str
        New names keyed by old; names that are not free are ignored.

    Returns
    -------
    Self
        A copy of the same class and label whose event spec has the
        dimensions renamed; the original is unchanged.
    """
    copy = self._with_declaration(
        self.event_spec.with_dim_names(**names), "with_dim_names", names
    )
    return _recorded_copy(copy, self)

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 OutputSpec.rename raises it.

ValueError

As OutputSpec.rename raises it.

Source code in probpipe/distributions/_distribution.py
def rename(
    self, renames: Mapping[str, str] | None = None, /, **keyword_renames: str
) -> Distribution:
    """Rename or move nodes of the event spec by their paths, ``old -> new``.

    The result is this law with :meth:`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
    ----------
    renames : Mapping[str, str], optional
        The new exact path of each node, keyed by the node's exact path.
    **keyword_renames : str
        Further renames, keyed by paths that are identifiers.

    Returns
    -------
    Distribution
        The renamed law under the same label; the original is unchanged.

    Raises
    ------
    KeyError
        If a key is not a path of the event spec.
    TypeError
        As :meth:`OutputSpec.rename` raises it.
    ValueError
        As :meth:`OutputSpec.rename` raises it.
    """
    renamed_event_spec = self.event_spec.rename(renames, **keyword_renames)
    all_renames = {**dict(renames or {}), **keyword_renames}
    if _renamed_law_factory is None:
        raise RuntimeError("the renamed law is not installed; import probpipe")
    return _renamed_law_factory(self, renamed_event_spec, all_renames)

__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 CoupledMarginal of it.

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
def __getitem__(self, paths: PathsLike, /) -> Distribution:
    """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
    ----------
    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.

    Returns
    -------
    Distribution
        This law itself, or a ``CoupledMarginal`` of it.

    Raises
    ------
    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.
    """
    read_paths = _read_event_paths(
        self.event_spec, self.label, paths, action=f"index {self.label!r} by"
    )
    if read_paths == _root_output_name(self.event_spec):
        return self
    if _coupled_marginal_factory is None:
        raise RuntimeError("the coupled marginal is not installed. Import probpipe")
    return _coupled_marginal_factory(self, read_paths)

__contains__(path)

Whether path is a str and self[path] gives a law: an event path, or a whole term's output.

Source code in probpipe/distributions/_distribution.py
def __contains__(self, path: object, /) -> bool:
    """Whether *path* is a ``str`` and ``self[path]`` gives a law: an event path, or a whole term's output."""
    return path in self.event_spec

__mul__(other)

Refuse * between distributions. Use & to merge them.

Parameters:

Name Type Description Default
other object

The right operand.

required

Returns:

Type Description
Any

NotImplemented for an operand of another kind.

Raises:

Type Description
TypeError

If other is a distribution or a conditional distribution.

Source code in probpipe/distributions/_distribution.py
def __mul__(self, other: object) -> Any:
    """Refuse ``*`` between distributions. Use ``&`` to merge them.

    Parameters
    ----------
    other : object
        The right operand.

    Returns
    -------
    Any
        ``NotImplemented`` for an operand of another kind.

    Raises
    ------
    TypeError
        If *other* is a distribution or a conditional distribution.
    """
    return _refuse_distribution_multiplication(other)

__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
def __bool__(self) -> NoReturn:
    """Refuse a truth value, so ``a and b`` raises. Use ``a & b`` to merge.

    Raises
    ------
    TypeError
        Always: a distribution has no truth value.
    """
    _refuse_distribution_truth_value()

__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 NotImplemented when other is neither distribution kind, so that Python raises TypeError.

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
def __and__(
    self, other: Distribution | ConditionalDistribution
) -> FactoredDistribution | FactoredConditionalDistribution:
    """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
    ----------
    other : Distribution or ConditionalDistribution
        The right operand, whose outputs this law's factors may condition
        on.

    Returns
    -------
    FactoredDistribution or FactoredConditionalDistribution
        The joint, or ``NotImplemented`` when *other* is neither
        distribution kind, so that Python raises ``TypeError``.

    Raises
    ------
    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.
    """
    return _merge_operands(self, other)

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
@classmethod
def from_batched_params(
    cls,
    *,
    label: str,
    batch_shape: tuple[int, ...] | None = None,
    **batched_params: Any,
) -> DistributionBatch:
    """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
    ----------
    label : str
        The batch's label.
    batch_shape : tuple of int, optional
        The batch axes, inferred from the parameters when omitted.
    **batched_params
        This class's constructor arguments, with the batch axes leading.

    Returns
    -------
    DistributionBatch
        The batch of these laws under the label *label*, with the batch axes
        as its batch shape.

    Raises
    ------
    NotImplementedError
        Always.
    """
    raise NotImplementedError("from_batched_params is not implemented yet")

__str__()

The law's notation, as prior(mu).

Source code in probpipe/distributions/_distribution.py
def __str__(self) -> str:
    """The law's :attr:`notation`, as ``prior(mu)``."""
    return self.notation

__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
def __repr__(self) -> str:
    """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',)``.
    """
    return _law_repr(self, self._repr_arguments())

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
def __init__(
    self,
    event_spec: OutputSpec | TermSpec,
    *,
    label: str | None = None,
    _provenance: Provenance | None = None,
    _annotations: Mapping[str, Any] | None = None,
):
    label = _constructor_label(self, label, DEFAULT_LABEL) if label is None else label
    _given_label(label, owner=public_class_name(type(self)))
    # ``_provenance`` and ``_annotations`` carry state a reconstruction
    # already holds and that construction cannot otherwise reach: provenance
    # is write-once, and annotations are written after construction, so a
    # rebuilt distribution would come back without either. Private, and the
    # reconstruction paths are the only callers.
    self._init_tracked(label, provenance=_provenance)
    _record_default_expression(self)
    self._init_annotations(_annotations)
    self._init_declaration(event_spec)

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 Weights object, which can be built from log weights, is adopted as it is.

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, ℙ by default.

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 BatchSpec event, its named levels must trail the stored atom levels; only the preceding axes index atoms and weights. One draw retains the event's levels, including levels of size zero. Nested batches are flattened into one batch, with outer levels before inner levels.

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 OutputSpec, or the outputs of event_spec are a record's fields for atoms that are not records.

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
def __init__(
    self,
    atoms: Batch | Array,
    weights: Array | Weights | None = None,
    *,
    output_name: str | None = None,
    label: str | None = None,
    level: str | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    if isinstance(atoms, str):
        raise TypeError(label_given_first("EmpiricalDistribution", "atoms", atoms))
    if isinstance(event_spec, OutputSpec) and isinstance(event_spec.term_spec, BatchSpec):
        event_spec = event_spec._with_term_spec(_flat_batch_spec(event_spec.term_spec))
    atom_spec = _atom_spec(atoms, event_spec)
    if level is not None and not isinstance(level, str):
        raise TypeError(f"level must be a string, got {type(level).__name__}")
    if level is not None and isinstance(atoms, Batch):
        raise TypeError(
            f"level applies only to atoms given as an array, but the batch {atoms.label!r} "
            f"already has the levels {list(atoms.level_names)}. Rename them with "
            f"with_level_names"
        )
    super().__init__(
        _atoms_declaration(atom_spec, output_name, event_spec),
        label=_constructor_label(self, label, DEFAULT_LABEL),
    )
    if isinstance(atoms, Batch):
        stored = atoms
    else:
        # An array's atoms form a whole-term event, whose output's name labels them
        # and names their level.
        name = _root_output_name(self.event_spec)
        on_level = name if level is None else level
        stored = _batch_form(name, atoms, on_level, atom_spec)
    atom_weights = _atom_weights(weights, stored, self.event_spec.term_spec)
    object.__setattr__(self, "_atoms", stored)
    object.__setattr__(self, "_w", atom_weights)
    # The weights the weighted helpers take, None when uniform. Read here, outside
    # any trace, so that a draw or a moment traced later reads a concrete array.
    probabilities = None if atom_weights.is_uniform else atom_weights.normalized
    object.__setattr__(self, "_p", probabilities)

atoms property

The atoms in the event's batch form, as stored.

weights property

The normalized weights, one per atom in row-major order over the atom axes.

num_atoms property

The number of atoms.

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 … when more remain, as [prior0(tau), prior1(tau)]. A batch of several axes reads as one flat list, and its repr gives the levels.

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 DistributionSpec, or an element is not a Distribution whose event spec unifies with it, naming the position; or label is omitted and there are no elements.

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, bytes, and a mapping are refused for both.

ValueError

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

Source code in probpipe/distributions/_batches.py
def __init__(
    self,
    elements: np.ndarray | Iterable[Distribution],
    /,
    level_names: NamesLike,
    *,
    label: str | None = None,
    element: DistributionSpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    super().__init__(
        elements,
        level_names,
        label=label,
        element=element,
        axes_per_level=axes_per_level,
        provenance=provenance,
    )

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
def __str__(self) -> 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``.
    """
    return _batch_notation(self)

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 Distribution, path is neither a string nor a list or tuple of strings, or parent is over a value with no paths.

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
def __init__(self, parent: Distribution, path: PathsLike) -> None:
    path = _read_event_paths(
        parent.event_spec, parent.label, path, action=f"index {parent.label!r} by"
    )
    declaration = _view_declaration(parent.event_spec, path)
    self._init_tracked(parent.label)
    self._init_annotations(None)
    object.__setattr__(self, "_parent", parent)
    object.__setattr__(self, "_path", path)
    self._init_declaration(declaration)
    self._store_expression(_marginal_expression_at(parent, path))
    self.with_provenance(
        Provenance.create("__getitem__", parents=[parent], metadata={"path": path})
    )

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 marginal labels it and holds the paths the parent holds fixed.

Raises:

Type Description
ResolutionError

If the parent has no exact marginal at the path. The error is not an AttributeError, so hasattr(coupled marginal, "raw") raises it rather than returning False, and each read tries the marginal again.

__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
def __getitem__(self, paths: PathsLike, /) -> Distribution:
    """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
    (:func:`marginal`), and it holds the paths this coupled marginal holds fixed.

    Parameters
    ----------
    paths : str, or list or tuple of str
        An event path of the coupled marginal, or a list of them.

    Returns
    -------
    Distribution
        This coupled marginal itself, or a law that reads the parent.

    Raises
    ------
    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.
    """
    request = _read_event_paths(
        self.event_spec,
        self.label,
        paths,
        action=f"index {self.label!r} by",
    )
    parent_request = self._parent_request(request)
    if parent_request.group is not None:
        return CoupledMarginal(self, request)
    if parent_request.paths == self._path:
        return self
    coupled_marginal = self._sub_view(request, parent_request.paths)
    return (
        coupled_marginal.rename(parent_request.renames)
        if parent_request.renames
        else coupled_marginal
    )

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
def with_dim_sizes(self, **sizes: int) -> CoupledMarginal:
    """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
    ----------
    **sizes : int
        Sizes for free dimensions of the coupled marginal's declaration.

    Returns
    -------
    CoupledMarginal
        The coupled marginal, under the same label, of the parent with the sizes bound.

    Raises
    ------
    ValueError
        If a name is not a free dimension of the coupled marginal's declaration.
    """
    unbound = set(sizes) - self.event_spec.term_spec.free_dims
    if unbound:
        raise ValueError(_no_free_dims(self, unbound, self.event_spec.term_spec.free_dims))
    return self._viewed(self._parent.with_dim_sizes(**sizes))

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
def with_dim_names(self, **names: str) -> CoupledMarginal:
    """Rename symbolic dimensions in the parent, and coupled marginal the result at the same path.

    Parameters
    ----------
    **names : str
        New names keyed by old; names that are not free are ignored.

    Returns
    -------
    CoupledMarginal
        The coupled marginal, under the same label, of the parent with the dimensions
        renamed.
    """
    return self._viewed(self._parent.with_dim_names(**names))

__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
def __repr__(self) -> str:
    """``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.
    """
    text = call_repr(
        self._repr_class_name(), [repr(self._parent)], [("path", repr(self._path))]
    )
    if self.label != _marginal_expression_at(self._parent, self._path).render_label():
        text = _method_call(text, "with_label", repr(self._displayed_label()))
    return text

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 __name__, and to ℙ for a lambda or a callable without a name.

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 RecordSpec while the returned law's outputs are a record's fields or it has more than one output, if event_spec names other outputs than the returned law or has another form, or if its type does not unify with the law's.

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
def conditional_distribution(
    fn: Callable[..., Distribution] | None = None,
    /,
    *,
    label: str | None = None,
    given_spec: InputSpec | Mapping[str, TermSpec | tuple] | RecordSpec | OutputSpec | None = None,
    event_spec: OutputSpec | TermSpec | None = None,
) -> Any:
    """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
    ----------
    fn : callable, optional
        The function of the given values that returns a law; without it, the
        result is a decorator.
    label : str, optional
        The kernel's label. Defaults to the function's ``__name__``, and to
        ``ℙ`` for a lambda or a callable without a name.
    given_spec : InputSpec, Mapping, RecordSpec, or OutputSpec, optional
        The specs of some or all inputs, keyed by parameter.
    event_spec : OutputSpec or TermSpec, optional
        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.

    Returns
    -------
    ConditionalDistribution or callable
        The kernel, or a decorator that builds it from a function.

    Raises
    ------
    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 ``RecordSpec`` while the
        returned law's outputs are a record's fields or it has more than one
        output, if *event_spec* names other outputs than the returned law or has
        another form, or if its type does not unify with the law's.

    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.
    """
    if isinstance(fn, str):
        raise TypeError(label_given_first("conditional_distribution", "function", fn))
    if label is not None:
        _given_label(label, owner="conditional_distribution")
    if fn is not None:
        return _function_kernel(label, fn, given_spec, event_spec)

    def decorate(function: Callable[..., Distribution]) -> ConditionalDistribution:
        return _function_kernel(label, function, given_spec, event_spec)

    return decorate

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, p by default. A subclass's constructor passes the label its caller gave, or its own default.

None
_provenance Provenance

The provenance of the kernel that a reconstruction rebuilds. By default the provenance stays unset until with_provenance attaches one.

None
_annotations Mapping[str, Any]

The annotations of the kernel that a reconstruction rebuilds, copied into the kernel's own store. By default annotations is None.

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 OutputSpec nor a RecordSpec.

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
def __init__(
    self,
    given_spec: InputSpec | Mapping[str, TermSpec | tuple] | RecordSpec | OutputSpec,
    event_spec: OutputSpec | TermSpec,
    *,
    label: str | None = None,
    _provenance: Provenance | None = None,
    _annotations: Mapping[str, Any] | None = None,
) -> None:
    label = _constructor_label(self, label, DEFAULT_LABEL) if label is None else label
    _given_label(label, owner=public_class_name(type(self)))
    self._init_tracked(label, provenance=_provenance)
    _record_default_expression(self)
    self._init_annotations(_annotations)
    self._init_declaration(given_spec, event_spec)

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
def with_dim_sizes(self, **sizes: int) -> Self:
    """Bind named symbolic dimensions on both sides.

    Parameters
    ----------
    **sizes : int
        Sizes for free dimensions of either side.

    Returns
    -------
    Self
        A copy of the same class and label with the sizes substituted on
        both sides; the original is unchanged.

    Raises
    ------
    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.
    """
    unbound = set(sizes) - self.spec.free_dims
    if unbound:
        raise ValueError(_no_free_dims(self, unbound, self.spec.free_dims))
    return self._with_declarations(
        self.given_spec.with_dim_sizes(**sizes),
        self.event_spec.with_dim_sizes(**sizes),
        "with_dim_sizes",
        sizes,
    )

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
def with_dim_names(self, **names: str) -> Self:
    """Rename symbolic dimensions on both sides, simultaneously.

    Parameters
    ----------
    **names : str
        New names keyed by old; names that are not free are ignored.

    Returns
    -------
    Self
        A copy of the same class and label with the dimensions renamed on
        both sides; the original is unchanged.
    """
    return self._with_declarations(
        self.given_spec.with_dim_names(**names),
        self.event_spec.with_dim_names(**names),
        "with_dim_names",
        names,
    )

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
def rename(
    self, renames: Mapping[str, str] | None = None, /, **keyword_renames: str
) -> ConditionalDistribution:
    """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
    :meth:`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
    ----------
    renames : Mapping[str, str], optional
        New names or paths keyed by the exact paths of the nodes they rename.
    **keyword_renames : str
        Further renames, keyed by paths that are identifiers.

    Returns
    -------
    ConditionalDistribution
        The renamed kernel under the same label; the original is unchanged.

    Raises
    ------
    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.
    """
    resolved_renames = _checked_path_renames(
        renames, keyword_renames, check_source=self._check_rename_source
    )
    input_moves = {
        source: target
        for source, target in resolved_renames.items()
        if self._is_input_path(source)
    }
    event_renames = {
        source: target
        for source, target in resolved_renames.items()
        if source not in input_moves
    }
    given_spec, origins = _moved_inputs(self.given_spec, input_moves)
    event_spec = self.event_spec.rename(event_renames) if event_renames else self.event_spec
    _check_disjoint_sides(given_spec, event_spec, repr(self.label))
    if _renamed_kernel_factory is None:
        raise RuntimeError("the renamed kernel is not installed; import probpipe")
    return _renamed_kernel_factory(
        self, given_spec, event_spec, origins, event_renames, resolved_renames
    )

__mul__(other)

Refuse * between distributions. Use & to merge them.

Parameters:

Name Type Description Default
other object

The right operand.

required

Returns:

Type Description
Any

NotImplemented for an operand of another kind.

Raises:

Type Description
TypeError

If other is a distribution or a conditional distribution.

Source code in probpipe/distributions/_conditional.py
def __mul__(self, other: object) -> Any:
    """Refuse ``*`` between distributions. Use ``&`` to merge them.

    Parameters
    ----------
    other : object
        The right operand.

    Returns
    -------
    Any
        ``NotImplemented`` for an operand of another kind.

    Raises
    ------
    TypeError
        If *other* is a distribution or a conditional distribution.
    """
    return _refuse_distribution_multiplication(other)

__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/_conditional.py
def __bool__(self) -> NoReturn:
    """Refuse a truth value, so ``a and b`` raises. Use ``a & b`` to merge.

    Raises
    ------
    TypeError
        Always: a distribution has no truth value.
    """
    _refuse_distribution_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
def __and__(
    self, other: Distribution | ConditionalDistribution
) -> FactoredConditionalDistribution | Distribution:
    """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 :meth:`Distribution.__and__`.
    """
    return _merge_operands(self, other)

__str__()

The kernel's notation, as glm(y | beta).

Source code in probpipe/distributions/_conditional.py
def __str__(self) -> str:
    """The kernel's :attr:`notation`, as ``glm(y | beta)``."""
    return self.notation

__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
def __repr__(self) -> str:
    """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.
    """
    arguments = [*self._repr_arguments(), ("given", format_names(self.given_spec))]
    return _law_repr(self, arguments)

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
def __init__(
    self,
    given_spec: InputSpec | Mapping[str, TermSpec | tuple] | RecordSpec | OutputSpec,
    event_spec: OutputSpec | TermSpec,
    *,
    label: str | None = None,
    _provenance: Provenance | None = None,
    _annotations: Mapping[str, Any] | None = None,
) -> None:
    label = _constructor_label(self, label, DEFAULT_LABEL) if label is None else label
    _given_label(label, owner=public_class_name(type(self)))
    self._init_tracked(label, provenance=_provenance)
    _record_default_expression(self)
    self._init_annotations(_annotations)
    self._init_declaration(given_spec, event_spec)

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
def __init__(
    self,
    given_spec: InputSpec | Mapping[str, TermSpec | tuple] | RecordSpec | OutputSpec,
    event_spec: OutputSpec | TermSpec,
    *,
    label: str | None = None,
    _provenance: Provenance | None = None,
    _annotations: Mapping[str, Any] | None = None,
) -> None:
    label = _constructor_label(self, label, DEFAULT_LABEL) if label is None else label
    _given_label(label, owner=public_class_name(type(self)))
    self._init_tracked(label, provenance=_provenance)
    _record_default_expression(self)
    self._init_annotations(_annotations)
    self._init_declaration(given_spec, event_spec)

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
def __init__(
    self,
    given_spec: InputSpec | Mapping[str, TermSpec | tuple] | RecordSpec | OutputSpec,
    event_spec: OutputSpec | TermSpec,
    *,
    label: str | None = None,
    _provenance: Provenance | None = None,
    _annotations: Mapping[str, Any] | None = None,
) -> None:
    label = _constructor_label(self, label, DEFAULT_LABEL) if label is None else label
    _given_label(label, owner=public_class_name(type(self)))
    self._init_tracked(label, provenance=_provenance)
    _record_default_expression(self)
    self._init_annotations(_annotations)
    self._init_declaration(given_spec, event_spec)

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 … when more remain. A batch of several axes reads as one flat list, and its repr gives the levels.

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 ConditionalDistributionSpec, or an element does not satisfy it, naming the position; or label is omitted and there are no elements.

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, bytes, and a mapping are refused for both.

ValueError

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

Source code in probpipe/distributions/_batches.py
def __init__(
    self,
    elements: np.ndarray | Iterable[ConditionalDistribution],
    /,
    level_names: NamesLike,
    *,
    label: str | None = None,
    element: ConditionalDistributionSpec | None = None,
    axes_per_level: AxisCountsLike | None = None,
    provenance: Provenance | None = None,
) -> None:
    super().__init__(
        elements,
        level_names,
        label=label,
        element=element,
        axes_per_level=axes_per_level,
        provenance=provenance,
    )

given_spec property

The input spec the elements share, a view on spec.

event_spec property

The event spec the elements share, a view on spec.

__str__()

The batch's notation and its levels, as glm(y | beta) over dataset.

Source code in probpipe/distributions/_batches.py
def __str__(self) -> str:
    """The batch's notation and its levels, as ``glm(y | beta) over dataset``."""
    return _batch_notation(self)

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 FactoredConditionalDistribution.

Source code in probpipe/distributions/_factored.py
def __init__(
    self,
    factors: Sequence[Factor],
    *,
    label: str | None = None,
    _scope: Mapping[str, int] | None = None,
    _output_name: str | None = None,
) -> None:
    expression = _product_of(factors) if label is None else None
    rendering = None
    if expression is not None:
        rendering = expression.label_rendering()
        label = rendering[0]
    graph = _factor_graph(factors, _scope)
    if graph.unmet is not None:
        raise ValueError(
            f"no factor of {label!r} defines {sorted(graph.unmet)}, which its factors "
            f"condition on; add a factor for them, or build a "
            f"FactoredConditionalDistribution"
        )
    super().__init__(
        _joint_declaration(graph, _output_name),
        label=label,
    )
    object.__setattr__(self, "_graph", graph)
    if expression is not None:
        self._store_expression(expression, rendering)

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
def with_dim_sizes(self, **sizes: int) -> Self:
    """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
    ----------
    **sizes : int
        Sizes for free dimensions of the joint.

    Returns
    -------
    Self
        The joint of the bound factors, under the same label.

    Raises
    ------
    ValueError
        If a name is not a free dimension of the joint.
    """
    rebuilt = _rebuilt(self, "with_dim_sizes", sizes, free=self.event_spec.term_spec.free_dims)
    return _recorded_copy(rebuilt, self)

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
def with_dim_names(self, **names: str) -> Self:
    """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
    ----------
    **names : str
        New names keyed by old; names that are not free are ignored.

    Returns
    -------
    Self
        The joint of the renamed factors, under the same label.
    """
    return _recorded_copy(_rebuilt(self, "with_dim_names", names), self)

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
def __init__(
    self,
    factors: Sequence[Factor],
    *,
    label: str | None = None,
    _scope: Mapping[str, int] | None = None,
    _output_name: str | None = None,
) -> None:
    expression = _product_of(factors) if label is None else None
    rendering = None
    if expression is not None:
        rendering = expression.label_rendering()
        label = rendering[0]
    graph = _factor_graph(factors, _scope)
    if graph.unmet is not None:
        raise ValueError(
            f"no factor of {label!r} defines {sorted(graph.unmet)}, which its factors "
            f"condition on; add a factor for them, or build a "
            f"FactoredConditionalDistribution"
        )
    super().__init__(
        _joint_declaration(graph, _output_name),
        label=label,
    )
    object.__setattr__(self, "_graph", graph)
    if expression is not None:
        self._store_expression(expression, rendering)

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 FactoredDistribution, or meet every given, which makes the joint a FactoredDistribution.

Source code in probpipe/distributions/_factored.py
def __init__(
    self,
    factors: Sequence[Factor],
    *,
    label: str | None = None,
    _scope: Mapping[str, int] | None = None,
    _output_name: str | None = None,
) -> None:
    expression = _product_of(factors) if label is None else None
    rendering = None
    if expression is not None:
        rendering = expression.label_rendering()
        label = rendering[0]
    graph = _factor_graph(factors, _scope)
    if graph.unmet is None:
        raise ValueError(
            f"the factors of {label!r} define every field they condition on; build a "
            f"FactoredDistribution instead"
        )
    super().__init__(
        graph.unmet,
        _joint_declaration(graph, _output_name),
        label=label,
    )
    object.__setattr__(self, "_graph", graph)
    if expression is not None:
        self._store_expression(expression, rendering)

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
def with_dim_sizes(self, **sizes: int) -> Self:
    """Bind named symbolic dimensions in every factor that declares them.

    Parameters
    ----------
    **sizes : int
        Sizes for free dimensions of either side.

    Returns
    -------
    Self
        The joint of the bound factors, under the same label.

    Raises
    ------
    ValueError
        If a name is not a free dimension of the joint.
    """
    return _rebuilt(self, "with_dim_sizes", sizes, free=self.spec.free_dims)

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
def with_dim_names(self, **names: str) -> Self:
    """Rename symbolic dimensions in every factor, simultaneously.

    Parameters
    ----------
    **names : str
        New names keyed by old; names that are not free are ignored.

    Returns
    -------
    Self
        The joint of the renamed factors, under the same label.
    """
    return _rebuilt(self, "with_dim_names", names)

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
def __init__(
    self,
    factors: Sequence[Factor],
    *,
    label: str | None = None,
    _scope: Mapping[str, int] | None = None,
    _output_name: str | None = None,
) -> None:
    expression = _product_of(factors) if label is None else None
    rendering = None
    if expression is not None:
        rendering = expression.label_rendering()
        label = rendering[0]
    graph = _factor_graph(factors, _scope)
    if graph.unmet is None:
        raise ValueError(
            f"the factors of {label!r} define every field they condition on; build a "
            f"FactoredDistribution instead"
        )
    super().__init__(
        graph.unmet,
        _joint_declaration(graph, _output_name),
        label=label,
    )
    object.__setattr__(self, "_graph", graph)
    if expression is not None:
        self._store_expression(expression, rendering)

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
def __init__(
    self,
    factors: Sequence[Factor],
    *,
    label: str | None = None,
    _scope: Mapping[str, int] | None = None,
    _output_name: str | None = None,
) -> None:
    expression = _product_of(factors) if label is None else None
    rendering = None
    if expression is not None:
        rendering = expression.label_rendering()
        label = rendering[0]
    graph = _factor_graph(factors, _scope)
    if graph.unmet is None:
        raise ValueError(
            f"the factors of {label!r} define every field they condition on; build a "
            f"FactoredDistribution instead"
        )
    super().__init__(
        graph.unmet,
        _joint_declaration(graph, _output_name),
        label=label,
    )
    object.__setattr__(self, "_graph", graph)
    if expression is not None:
        self._store_expression(expression, rendering)

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
def __init__(
    self,
    factors: Sequence[Factor],
    *,
    label: str | None = None,
    _scope: Mapping[str, int] | None = None,
    _output_name: str | None = None,
) -> None:
    expression = _product_of(factors) if label is None else None
    rendering = None
    if expression is not None:
        rendering = expression.label_rendering()
        label = rendering[0]
    graph = _factor_graph(factors, _scope)
    if graph.unmet is None:
        raise ValueError(
            f"the factors of {label!r} define every field they condition on; build a "
            f"FactoredDistribution instead"
        )
    super().__init__(
        graph.unmet,
        _joint_declaration(graph, _output_name),
        label=label,
    )
    object.__setattr__(self, "_graph", graph)
    if expression is not None:
        self._store_expression(expression, rendering)

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 Normal for a tfd.Normal.

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 OutputSpec or is in the positional form over a record.

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
@_recording_arguments
def __init__(
    self,
    output_name: str,
    backend_dist: tfd.Distribution,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    if not isinstance(backend_dist, tfd.Distribution):
        raise TypeError(
            f"backend_dist must be a backend distribution, got {type(backend_dist).__name__}"
        )
    owner = _class_label(self)
    default = type(backend_dist).__name__ if owner == "TFPDistribution" else owner
    backend_dist = self._reinterpreted(backend_dist)
    self._tfp_dist = backend_dist
    produced = NumericArraySpec(
        tuple(backend_dist.event_shape), backend_dist.dtype, self._event_support()
    )
    declaration = _whole_term_event(output_name, produced, event_spec, owner)
    super().__init__(
        declaration,
        label=_constructor_label(self, label, default),
    )

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
def __init_subclass__(cls, **kwargs: Any) -> None:
    """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 :meth:`__reduce__` rebuilds the
    family from.
    """
    super().__init_subclass__(**kwargs)
    for protocol in vars(cls).get("_backend_capabilities", ()):
        for method, implementation in _BACKEND_METHODS[protocol].items():
            if not _implements(cls, method):
                setattr(cls, method, implementation)
    if "__init__" in vars(cls):
        cls.__init__ = _recording_arguments(vars(cls)["__init__"])

__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
def __reduce__(self) -> tuple[Any, ...]:
    """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.
    """
    arguments = getattr(self, "_constructor_arguments", None)
    if arguments is None:
        return super().__reduce__()
    instance_dict, slots = self.__getstate__()
    rebuilt = ("_tfp_dist", "_constructor_arguments")
    kept = {key: value for key, value in (instance_dict or {}).items() if key not in rebuilt}
    return (
        _rebuilt_family,
        (type(self), *arguments),
        (kept or None, slots),
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    loc: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._loc, self._scale) = _promote_floats(loc, scale)
    super().__init__(
        output_name,
        tfd.Normal(loc=self._loc, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    alpha: ArrayLike,
    beta: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._alpha, self._beta) = _promote_floats(alpha, beta)
    super().__init__(
        output_name,
        tfd.Beta(concentration1=self._alpha, concentration0=self._beta),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    concentration: ArrayLike,
    rate: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._concentration, self._rate) = _promote_floats(concentration, rate)
    super().__init__(
        output_name,
        tfd.Gamma(concentration=self._concentration, rate=self._rate),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    concentration: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._concentration, self._scale) = _promote_floats(concentration, scale)
    super().__init__(
        output_name,
        tfd.InverseGamma(concentration=self._concentration, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    rate: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    self._rate = _as_float_array(rate)
    super().__init__(
        output_name, tfd.Exponential(rate=self._rate), label=label, event_spec=event_spec
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    loc: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._loc, self._scale) = _promote_floats(loc, scale)
    super().__init__(
        output_name,
        tfd.LogNormal(loc=self._loc, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    df: ArrayLike,
    loc: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._df, self._loc, self._scale) = _promote_floats(df, loc, scale)
    super().__init__(
        output_name,
        tfd.StudentT(df=self._df, loc=self._loc, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    low: ArrayLike,
    high: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._low, self._high) = _promote_floats(low, high)
    super().__init__(
        output_name,
        tfd.Uniform(low=self._low, high=self._high),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    loc: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._loc, self._scale) = _promote_floats(loc, scale)
    super().__init__(
        output_name,
        tfd.Cauchy(loc=self._loc, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    loc: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._loc, self._scale) = _promote_floats(loc, scale)
    super().__init__(
        output_name,
        tfd.Laplace(loc=self._loc, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    self._scale = _as_float_array(scale)
    super().__init__(
        output_name, tfd.HalfNormal(scale=self._scale), label=label, event_spec=event_spec
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    loc: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._loc, self._scale) = _promote_floats(loc, scale)
    super().__init__(
        output_name,
        tfd.HalfCauchy(loc=self._loc, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    concentration: ArrayLike,
    scale: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._concentration, self._scale) = _promote_floats(concentration, scale)
    super().__init__(
        output_name,
        tfd.Pareto(concentration=self._concentration, scale=self._scale),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    loc: ArrayLike,
    scale: ArrayLike,
    low: ArrayLike,
    high: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (self._loc, self._scale, self._low, self._high) = _promote_floats(loc, scale, low, high)
    super().__init__(
        output_name,
        tfd.TruncatedNormal(loc=self._loc, scale=self._scale, low=self._low, high=self._high),
        label=label,
        event_spec=event_spec,
    )

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    *,
    probs: ArrayLike | None = None,
    logits: ArrayLike | None = None,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    if (probs is None) == (logits is None):
        raise ValueError("exactly one of probs or logits must be provided")
    if probs is not None:
        self._probs = _as_float_array(probs)
        self._logits = None
        backend = tfd.Bernoulli(probs=self._probs)
    else:
        self._logits = _as_float_array(logits)
        self._probs = None
        backend = tfd.Bernoulli(logits=self._logits)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    total_count: ArrayLike,
    *,
    probs: ArrayLike | None = None,
    logits: ArrayLike | None = None,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    if (probs is None) == (logits is None):
        raise ValueError("exactly one of probs or logits must be provided")
    if probs is not None:
        _, (self._total_count, self._probs) = _promote_floats(total_count, probs)
        self._logits = None
        backend = tfd.Binomial(total_count=self._total_count, probs=self._probs)
    else:
        _, (self._total_count, self._logits) = _promote_floats(total_count, logits)
        self._probs = None
        backend = tfd.Binomial(total_count=self._total_count, logits=self._logits)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    rate: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    self._rate = _as_float_array(rate)
    backend = tfd.Poisson(rate=self._rate)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    *,
    probs: ArrayLike | None = None,
    logits: ArrayLike | None = None,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    if (probs is None) == (logits is None):
        raise ValueError("exactly one of probs or logits must be provided")
    if probs is not None:
        self._probs = _as_float_array(probs)
        self._logits = None
        backend = tfd.Categorical(probs=self._probs)
    else:
        self._logits = _as_float_array(logits)
        self._probs = None
        backend = tfd.Categorical(logits=self._logits)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    total_count: ArrayLike,
    *,
    probs: ArrayLike | None = None,
    logits: ArrayLike | None = None,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    if (probs is None) == (logits is None):
        raise ValueError("exactly one of probs or logits must be provided")
    if probs is not None:
        _, (self._total_count, self._probs) = _promote_floats(total_count, probs)
        self._logits = None
        backend = tfd.NegativeBinomial(total_count=self._total_count, probs=self._probs)
    else:
        _, (self._total_count, self._logits) = _promote_floats(total_count, logits)
        self._probs = None
        backend = tfd.NegativeBinomial(total_count=self._total_count, logits=self._logits)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

ValueError

If not exactly one of scale_tril and cov is given, the trailing axes of cov are not (d, d) for the length d of loc, or event_spec declares a type that one draw does not conform to.

Source code in probpipe/families/_multivariate.py
def __init__(
    self,
    output_name: str,
    loc: ArrayLike,
    scale_tril: ArrayLike | None = None,
    *,
    cov: LinOp | ArrayLike | None = None,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    if scale_tril is not None and cov is not None:
        raise ValueError("scale_tril and cov cannot both be given; pass one of them")

    operator = cov if isinstance(cov, LinOp) else None
    if operator is not None:
        cov = operator.to_dense()
    if scale_tril is not None:
        _, (loc, scale_tril) = _promote_floats(loc, scale_tril)
    elif cov is not None:
        _, (loc, cov) = _promote_floats(loc, cov)
    else:
        raise ValueError("one of scale_tril or cov must be provided")

    if loc.ndim == 0:
        loc = loc.reshape(1)

    if cov is not None:
        d = loc.shape[-1]
        if cov.ndim < 2 or cov.shape[-2:] != (d, d):
            raise ValueError(
                f"cov shape {cov.shape} does not match loc length {d}: its trailing axes "
                f"must be ({d}, {d})"
            )
        scale_tril, positive_definite = _covariance_factor(cov)
    else:
        positive_definite = _nonsingular_factor(scale_tril)

    self._loc = loc
    self._scale_tril = scale_tril
    self._dense_cov = cov
    self._given_cov = operator if operator is not None else cov
    self._positive_definite = positive_definite
    backend = tfd.MultivariateNormalTriL(loc=loc, scale_tril=scale_tril)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    concentration: ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    concentration = _as_float_array(concentration)
    if concentration.ndim == 0:
        raise ValueError(f"concentration must be at least 1-D, got shape {concentration.shape}")

    self._concentration = concentration
    backend = tfd.Dirichlet(concentration=concentration)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    total_count: int | ArrayLike,
    probs: ArrayLike | None = None,
    logits: ArrayLike | None = None,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    if (probs is None) == (logits is None):
        raise ValueError("exactly one of probs or logits must be provided")

    if probs is not None:
        _, (total_count, probs) = _promote_floats(total_count, probs)
        self._probs = probs
        self._logits = None
        backend = tfd.Multinomial(total_count=total_count, probs=probs)
    else:
        _, (total_count, logits) = _promote_floats(total_count, logits)
        self._logits = logits
        self._probs = None
        backend = tfd.Multinomial(total_count=total_count, logits=logits)

    self._total_count = total_count
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    df: float | ArrayLike,
    scale_tril: ArrayLike | None = None,
    *,
    scale: ArrayLike | None = None,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    if scale_tril is not None and scale is not None:
        raise ValueError("scale_tril and scale cannot both be given; pass one of them")
    if scale_tril is None and scale is None:
        raise ValueError("one of scale_tril or scale must be provided")

    if scale is not None:
        _, (df, scale) = _promote_floats(df, scale)
        scale_tril = jnp.linalg.cholesky(scale)
    else:
        _, (df, scale_tril) = _promote_floats(df, scale_tril)

    self._df = df
    self._scale_tril = scale_tril
    backend = tfd.WishartTriL(df=df, scale_tril=scale_tril)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 OutputSpec(theta=NumericArraySpec((3,))).

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    mean_direction: ArrayLike,
    concentration: float | ArrayLike,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
):
    _, (mean_direction, concentration) = _promote_floats(mean_direction, concentration)

    self._mean_direction = mean_direction
    self._concentration = concentration
    backend = tfd.VonMisesFisher(mean_direction=mean_direction, concentration=concentration)
    super().__init__(output_name, backend, label=label, event_spec=event_spec)

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 SupportsSampling.

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, BootstrapReplicateDistribution by default.

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 OutputSpec or is in the positional form over a record.

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
def __init__(
    self,
    output_name: str,
    source: SupportsSampling,
    replicate_size: int | None = None,
    *,
    label: str | None = None,
    level: str | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    law = _sampling_source(source)
    size = _replicate_size(law, replicate_size)
    on_level = _replicate_level(law, level)
    term = _replicate_spec(law, size, on_level)
    owner = _class_label(self)
    super().__init__(
        _whole_term_event(output_name, term, event_spec, owner),
        label=_constructor_label(self, label, owner),
    )
    self._source = law
    self._replicate_size = size
    self._level = on_level

source property

The law a replicate draws from.

replicate_size property

The number of draws in one replicate.

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 SupportsSampling.

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, BootstrapDistribution by default, which also labels each drawn empirical measure.

None
level str

The level the atoms of a drawn measure lie on, defaulting as for BootstrapReplicateDistribution.

None
event_spec OutputSpec

An event spec naming output_name, which gives the type of one draw.

None

Raises:

Type Description
(TypeError, ValueError)

As BootstrapReplicateDistribution raises.

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
def __init__(
    self,
    output_name: str,
    source: SupportsSampling,
    replicate_size: int | None = None,
    *,
    label: str | None = None,
    level: str | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    law = _sampling_source(source)
    size = _replicate_size(law, replicate_size)
    on_level = _replicate_level(law, level)
    term = DistributionSpec(law.event_spec)
    if event_spec is not None:
        term = _whole_term_event(output_name, term, event_spec, _class_label(self))
    super().__init__(output_name, term, label=label)
    self._source = law
    self._replicate_size = size
    self._level = on_level

source property

The law a replicate draws from.

replicate_size property

The number of atoms of a drawn measure.

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 selects Scott's 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 by default.

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, KDEDistribution by default.

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 NumericRecordBatch, a list or a tuple of atoms holds an entry that is not a number, kernel is not a SmoothingKernel class, output_name is missing for array atoms or given for record atoms, label is not a non-empty string, event_spec is not an OutputSpec, or event_spec is in the positional form over a record for array atoms.

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
def __init__(
    self,
    atoms: Array | NumericRecordBatch,
    bandwidth: ArrayLike | NumericRecord | str | None = None,
    weights: Array | Weights | None = None,
    kernel: type[SmoothingKernel] = GaussianKernel,
    *,
    output_name: str | None = None,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    if isinstance(atoms, str):
        raise TypeError(label_given_first("KDEDistribution", "atoms", atoms))
    if not (isinstance(kernel, type) and issubclass(kernel, SmoothingKernel)):
        raise TypeError(
            f"kernel must be a SmoothingKernel subclass such as GaussianKernel, got {kernel!r}"
        )
    stored, atom_spec = _kde_atoms(atoms)
    owner = _class_label(self)
    declared = _atoms_declaration(atom_spec, output_name, event_spec, owner)
    super().__init__(
        declared,
        label=_constructor_label(self, label, owner),
    )
    centers = _flat_centers(stored, _KDE_NAMES)
    atom_weights = _kde_weights(weights, centers.shape[0])
    if bandwidth is None or isinstance(bandwidth, str):
        scales = _selected_bandwidth(bandwidth or "scott", centers, atom_weights)
    else:
        scales = bandwidth
        # Checked here first, so that a bad bandwidth is reported in the KDE's terms.
        fields = stored.event_template if isinstance(stored, NumericRecordBatch) else None
        _flat_scales(scales, centers, fields, _KDE_NAMES)
    bank = kernel.build_kernels(stored, scales)
    object.__setattr__(self, "_atoms", stored)
    object.__setattr__(self, "_bandwidth", scales)
    object.__setattr__(self, "_kernel", kernel)
    object.__setattr__(self, "_bank", bank)
    object.__setattr__(self, "_w", atom_weights)
    probabilities = None if atom_weights.is_uniform else atom_weights.normalized
    object.__setattr__(self, "_p", probabilities)

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, (n, *event). A batch of numeric records is flattened to its coordinates, (n, d).

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 K in each coordinate, so the copy with scale h has the variance h² * variance in that coordinate.

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
def __init__(
    self, centers: ArrayLike | NumericRecordBatch, scales: ArrayLike | NumericRecord
) -> None:
    fields = centers.event_template if isinstance(centers, NumericRecordBatch) else None
    self._centers = _flat_centers(centers)
    self._scales = _flat_scales(scales, self._centers, fields)

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 SmoothingKernel.

required
scales ArrayLike or NumericRecord

The scales, broadcast against the centers as for SmoothingKernel.

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
@classmethod
@abstractmethod
def build_kernels(
    cls, centers: ArrayLike | NumericRecordBatch, scales: ArrayLike | NumericRecord
) -> SmoothingKernel:
    """The bank of copies placed at *centers* with *scales*, one copy per center.

    Parameters
    ----------
    centers : ArrayLike or NumericRecordBatch
        One center per atom along the leading axis, as for :class:`SmoothingKernel`.
    scales : ArrayLike or NumericRecord
        The scales, broadcast against the centers as for :class:`SmoothingKernel`.

    Returns
    -------
    SmoothingKernel
        An instance of this kernel class holding the placed copies.

    Raises
    ------
    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.
    """

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
def __init__(
    self, centers: ArrayLike | NumericRecordBatch, scales: ArrayLike | NumericRecord
) -> None:
    fields = centers.event_template if isinstance(centers, NumericRecordBatch) else None
    self._centers = _flat_centers(centers)
    self._scales = _flat_scales(scales, self._centers, fields)

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
@classmethod
def build_kernels(
    cls, centers: ArrayLike | NumericRecordBatch, scales: ArrayLike | NumericRecord
) -> GaussianKernel:
    """The bank of normal copies placed at *centers* with the standard deviations *scales*."""
    return cls(centers, scales)

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
def __init__(
    self, centers: ArrayLike | NumericRecordBatch, scales: ArrayLike | NumericRecord
) -> None:
    fields = centers.event_template if isinstance(centers, NumericRecordBatch) else None
    self._centers = _flat_centers(centers)
    self._scales = _flat_scales(scales, self._centers, fields)

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
@classmethod
def build_kernels(
    cls, centers: ArrayLike | NumericRecordBatch, scales: ArrayLike | NumericRecord
) -> EpanechnikovKernel:
    """The bank of Epanechnikov copies placed at *centers* with the half-widths *scales*."""
    return cls(centers, scales)

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, mixture by default. The default's notation lists the components, up to eight of them, as mixture([a(x), b(x)]).

None

Raises:

Type Description
TypeError

If components is a string, a component is not a Distribution, or label is not a non-empty string.

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
def __init__(
    self, components: Sequence[Distribution], weights: ArrayLike, *, label: str | None = None
) -> None:
    laws = _components(components)
    store = np.empty(len(laws), dtype=object)
    for index, law in enumerate(laws):
        store[index] = law
    expression = Applied("mixture", (_collection_expression(store),))
    rendering = expression.label_rendering()
    object.__setattr__(self, "_components", laws)
    object.__setattr__(self, "_weights", _weights(weights, len(laws)))
    super().__init__(
        _declaration(laws),
        label=_constructor_label(self, label, rendering[0]),
    )
    if label is None:
        self._store_expression(expression, rendering)
        _record_default_expression(self)

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 X, whose draws are arrays.

required
bijector Function

The invertible map f, claiming the inverse and the log-determinant of its Jacobian; a backend bijector enters as such a Function.

required
label str

The transformed law's label, BijectorTransformedDistribution by default.

None

Raises:

Type Description
TypeError

If base is not a Distribution whose draws are arrays, output_name is not a string, label is not a non-empty string, or bijector is neither a Function nor a backend bijector.

ValueError

If output_name is not a valid output name.

ResolutionError

If bijector does not claim SupportsInverse, or its guard rejects, or it does not claim SupportsLogDetJacobian.

Source code in probpipe/families/_transformed.py
def __init__(
    self,
    output_name: str,
    base: Distribution,
    bijector: Function | Any,
    *,
    label: str | None = None,
) -> None:
    owner = _class_label(self)
    label = _constructor_label(self, label, owner)
    if not isinstance(base, Distribution):
        raise TypeError(
            f"base of BijectorTransformedDistribution must be a Distribution, got "
            f"{type(base).__name__}"
        )
    base_kind = base.event_spec.term_spec
    if not isinstance(base_kind, NumericArraySpec):
        drawn = "records" if _has_record_outputs(base.event_spec) else type(base_kind).__name__
        raise TypeError(
            f"BijectorTransformedDistribution needs a base that draws numeric arrays, but "
            f"{base.label!r} draws {drawn}"
        )
    bijector = _as_bijector(bijector)
    inverse = _not_invertible(bijector)
    if inverse is not None or not isinstance(bijector, SupportsLogDetJacobian):
        if isinstance(bijector, SupportsLogDetJacobian):
            reason = inverse
        elif isinstance(bijector, SupportsInverse):
            reason = "does not implement SupportsLogDetJacobian" + (
                f" and {inverse}" if inverse is not None else ""
            )
        else:
            reason = "does not implement SupportsInverse and SupportsLogDetJacobian"
        raise ResolutionError(
            f"BijectorTransformedDistribution {label!r} needs an invertible bijector with a "
            f"log-det Jacobian, but {bijector.label!r} {reason}"
        )
    base_spec = base.event_spec.term_spec
    point = jax.ShapeDtypeStruct(tuple(base_spec.shape), base_spec.dtype or jnp.float32)
    image = jax.eval_shape(_forward(bijector), point)
    object.__setattr__(self, "_base", base)
    object.__setattr__(self, "_bijector", bijector)
    image_spec = NumericArraySpec(tuple(image.shape), image.dtype, _image(bijector))
    super().__init__(
        _whole_term_event(output_name, image_spec, None, owner),
        label=label,
    )
    self.with_provenance(
        Provenance.create("transform", parents=[base], metadata={"bijector": bijector.label})
    )

base property

The law of X.

bijector property

The invertible map f.

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 X, whose numeric event is op's input.

required
op LinOp

The linear map.

required
label str

The pushforward's label, LinearPushforwardDistribution by default.

None

Raises:

Type Description
NotImplementedError

Always, until the linear evaluation rule is implemented.

Source code in probpipe/families/_transformed.py
def __init__(
    self, output_name: str, base: Distribution, op: LinOp, *, label: str | None = None
) -> None:
    raise NotImplementedError("LinearPushforwardDistribution is not implemented yet")

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 ·, as a·b, and the notation reads factor by factor.

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 FactoredDistribution.

Source code in probpipe/families/_gaussian.py
def __init__(
    self,
    factors: Sequence[Distribution | ConditionalDistribution],
    *,
    label: str | None = None,
    _scope: Mapping[str, int] | None = None,
    _output_name: str | None = None,
) -> None:
    super().__init__(
        factors,
        _scope=_scope,
        _output_name=_output_name,
        label=label,
    )
    if not _jointly_gaussian(self.factors):
        kinds = sorted(
            {type(factor).__name__ for factor in self.factors if not _is_gaussian(factor)}
        )
        raise TypeError(
            f"FactoredMultivariateGaussian {self.label!r} accepts only Normal or "
            f"MultivariateNormal factors, or Gaussian joints of them, got {kinds}"
        )

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 A's output.

required
cov LinOp

The covariance of the event, square over A's output.

required
label str

The kernel's label, LinearGaussianConditional by default.

None

Raises:

Type Description
NotImplementedError

Always, until LinOp declares its input and output type.

Source code in probpipe/families/_conditional.py
def __init__(
    self, output_name: str, A: LinOp, b: Array, cov: LinOp, *, label: str | None = None
) -> None:
    raise NotImplementedError("LinearGaussianConditional is not implemented yet")

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, ℙ by default.

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 (obs, features), fixed at construction.

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 GLMFamily, link is not a Function, event_spec is not an OutputSpec, or a dispersion is given to a family that has none.

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
def glm_likelihood(
    output_name: str,
    family: GLMFamily,
    link: Function | None = None,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
    X: Array | None = None,
    dispersion: ArrayLike | None = None,
) -> ConditionalDistribution:
    """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
    ----------
    output_name : str
        The name of the kernel's one output, which names the response.
    family : GLMFamily
        The response family.
    link : Function, optional
        The invertible link from the mean to the linear predictor. Defaults to
        the family's canonical link.
    label : str, optional
        The kernel's label, ``ℙ`` by default.
    event_spec : OutputSpec, optional
        An event spec naming *output_name*, which gives the response's type,
        passed through to the family.
    X : Array, optional
        The design matrix, of shape ``(obs, features)``, fixed at construction.
    dispersion : ArrayLike, optional
        The dispersion, fixed at construction; only for a family that has one.

    Returns
    -------
    ConditionalDistribution
        The GLM kernel, which claims conditional sampling, log-density, mean,
        variance, and covariance.

    Raises
    ------
    TypeError
        If *family* is not a ``GLMFamily``, *link* is not a ``Function``,
        *event_spec* is not an ``OutputSpec``, or a dispersion is given to a
        family that has none.
    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.
    """
    return _GLMLikelihood(
        output_name,
        family,
        family.canonical_link if link is None and isinstance(family, GLMFamily) else link,
        label=label,
        event_spec=event_spec,
        X=X,
        dispersion=dispersion,
    )

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
def __init__(self) -> None:
    _require_invertible(self.canonical_link, type(self).__name__)

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 OutputSpec.

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
@abstractmethod
def build(
    self,
    output_name: str,
    mean: Array,
    dispersion: ArrayLike | None = None,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
) -> Distribution:
    """The law of ``len(mean)`` conditionally independent observations with these means.

    Parameters
    ----------
    output_name : str
        The name of the law's one output, which names its draws.
    mean : Array
        One mean per observation, a vector.
    dispersion : ArrayLike, optional
        The dispersion, required when the family has one and refused
        otherwise.
    label : str, optional
        The law's label, the class name of the law's family by default.
    event_spec : OutputSpec, optional
        An event spec naming *output_name*, which gives the type of one
        draw; the family completes it with the response vector.

    Returns
    -------
    Distribution
        The law of the response vector, one entry per observation.

    Raises
    ------
    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 ``OutputSpec``.
    ValueError
        If *mean* is not a vector, or *event_spec* declares a type the
        response vector does not conform to.
    """

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
def __init__(self) -> None:
    _require_invertible(self.canonical_link, type(self).__name__)

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
def build(
    self,
    output_name: str,
    mean: Array,
    dispersion: ArrayLike | None = None,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
) -> Distribution:
    """Independent normal observations with these means and the scale *dispersion*.

    Parameters and errors are those of :meth:`GLMFamily.build`.
    """
    mean = _observation_vector(mean, f"{type(self).__name__}.build", "mean")
    scale = self._dispersion(dispersion, mean)
    return Normal(output_name, mean, scale, label=label, event_spec=event_spec)

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
def __init__(self) -> None:
    _require_invertible(self.canonical_link, type(self).__name__)

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
def build(
    self,
    output_name: str,
    mean: Array,
    dispersion: ArrayLike | None = None,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
) -> Distribution:
    """Independent Bernoulli observations with the probabilities *mean*.

    Parameters and errors are those of :meth:`GLMFamily.build`.
    """
    mean = _observation_vector(mean, f"{type(self).__name__}.build", "mean")
    self._dispersion(dispersion, mean)
    return Bernoulli(output_name, probs=mean, label=label, event_spec=event_spec)

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
def __init__(self) -> None:
    _require_invertible(self.canonical_link, type(self).__name__)

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
def build(
    self,
    output_name: str,
    mean: Array,
    dispersion: ArrayLike | None = None,
    *,
    label: str | None = None,
    event_spec: OutputSpec | None = None,
) -> Distribution:
    """Independent Poisson observations with the rates *mean*.

    Parameters and errors are those of :meth:`GLMFamily.build`.
    """
    mean = _observation_vector(mean, f"{type(self).__name__}.build", "mean")
    self._dispersion(dispersion, mean)
    return Poisson(output_name, mean, label=label, event_spec=event_spec)

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 .stan file that holds the program.

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 Distribution.

None
label str

The label of the kernel or of the posterior, StanModel by default.

None

Raises:

Type Description
ImportError

If bridgestan is not installed, or its stanc compiler is absent and cannot be fetched.

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
def __init__(
    self,
    stan_file: str,
    *,
    data: Mapping[str, Any] | None = None,
    label: str | None = None,
) -> None:
    program = _StanProgram.read(stan_file)
    bound = dict(data or {})
    super().__init__(
        program.given_spec(bound),
        OutputSpec(program.parameter_record(bound)),
        label=_constructor_label(self, label, "StanModel"),
    )
    object.__setattr__(self, "_program", program)
    object.__setattr__(self, "_data", bound)

stan_file property

The Stan program's file.

data property

The data-block variables bound at construction or by condition_on.

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 pymc.Model, whose observed variables take their observed values from arguments that default to None.

required
label str

The label of the law or of the kernel, PyMCModel by default.

None

Raises:

Type Description
ImportError

If PyMC is not installed, or if its release is older than the floor of the pymc extra.

TypeError

If model_fn cannot be built with its arguments' defaults.

Source code in probpipe/families/_programs.py
def __init__(self, model_fn: Callable[..., Any], *, label: str | None = None) -> None:
    program = model_fn if isinstance(model_fn, _PyMCProgram) else _PyMCProgram(model_fn)
    super().__init__(
        OutputSpec(program.event_record(symbolic=False)),
        label=_constructor_label(self, label, "PyMCModel"),
    )
    self._program = program